在 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.