在 Golang 中根據指定分隔符分割切片


在 Golang 中,有多種方法可以根據指定的分割符分割切片。這可以透過使用內建函式和方法來實現。在本文中,我們將探討一些在 Golang 中分割切片的一些常用方法。

使用 strings.SplitAfter 函式

Golang 中的 strings 包提供了一個 SplitAfter 函式,該函式在指定的分割符之後分割字串或位元組切片,並將結果作為字串切片返回。

示例

package main

import (
   "fmt"
   "strings"
)

func main() {
   slice := []string{"apple_", "banana_", "cherry_", "date_"}
   sep := "_"
   result := make([]string, 0)

   for _, s := range slice {
      result = append(result, strings.SplitAfter(s, sep)...)
   }

   fmt.Println(result)
}

輸出

[apple_  banana_  cherry_  date_ ]

使用 bytes.SplitAfter 函式

Golang 中的 bytes 包提供了一個 SplitAfter 函式,該函式在指定的分割符之後分割位元組切片,並將結果作為位元組切片切片返回。

示例

package main

import (
   "bytes"
   "fmt"
)

func main() {
   slice := [][]byte{{97, 112, 112, 108, 101, 95}, {98, 97, 110, 97, 110, 97, 95}, {99, 104, 101, 114, 114, 121, 95}, {100, 97, 116, 101, 95}}
   sep := []byte{'_'}
   result := make([][]byte, 0)

   for _, s := range slice {
      result = append(result, bytes.SplitAfter(s, sep)...)
   }
   fmt.Println(result)
}

輸出

[[97 112 112 108 101 95] [] [98 97 110 97 110 97 95] [] [99 104 101 114 114 121 95] [] [100 97 116 101 95] []]

使用自定義函式

我們還可以編寫自定義函式來根據指定的分割符分割切片。

示例

package main

import (
   "fmt"
   "strings"
)

func splitAfter(slice []string, sep string) []string {
   result := make([]string, 0)

   for _, s := range slice {
      index := 0
      for {
         i := strings.Index(s[index:], sep)
         if i == -1 {
            break
         }
         result = append(result, s[index:i+index+len(sep)])
         index = i + index + len(sep)
      }
      result = append(result, s[index:])
   }
   return result
}

func main() {
   slice := []string{"apple_", "banana_", "cherry_", "date_"}
   sep := "_"
   result := splitAfter(slice, sep)

   fmt.Println(result)
}

輸出

[apple_ banana_ cherry_ date_]

結論

在本文中,我們探討了一些在 Golang 中根據指定的分割符分割切片的一些常用方法。我們使用了 strings 和 bytes 包提供的內建函式,以及自定義函式。根據需求和切片型別,我們可以選擇合適的方法在 Golang 中分割切片。

更新於: 2023年4月19日

82 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.