Golang?分割字符串的實現(xiàn)示例
在開發(fā)過程中,很多時候我們有分割字符串的需求,即把一個字符串按照某種分割符進行切割。
在 Go 語言中,分割字符串我們可以分為幾種情況,分別為:
- 按空格分割
- 按字符分割
- 按字符串分割
下面分別講解使用 Golang 如何實現(xiàn)不同方式的字符串分割。
1.按空格分割
ss := strings.Fields(s)
示例:
package main
import (
?? ?"fmt"
?? ?"strings"
)
func main() {
?? ?fmt.Printf("Fields are: %q", strings.Fields(" ?foo bar ?baz ? "))
}輸出:
Fields are: ["foo" "bar" "baz"]
2.按字符/字符串分割
ss := strings.Split(s, sep)
可以指定一個字符串作為分隔符,可以指定單個字符作為分隔符,因為單個字符也是一個字符串。
示例:
package main
import (
?? ?"fmt"
?? ?"strings"
)
func main() {
?? ?fmt.Printf("%q\n", strings.Split("a,b,c", ","))
?? ?fmt.Printf("%q\n", strings.Split("a man a plan a canal panama", "a "))
?? ?fmt.Printf("%q\n", strings.Split(" xyz ", ""))
?? ?fmt.Printf("%q\n", strings.Split("", ","))
}輸出:
["a" "b" "c"]
["" "man " "plan " "canal panama"]
[" " "x" "y" "z" " "]
[""]
注意,如果待分割串為空串,strings.Split 將返回包含一個空串的切片。
如果希望返回 nil 切片,可以做一下封裝。
func Split(s, sep string) []string {
if s == "" {
return nil
}
return strings.Split(s, sep)
}
3.按多個字符分割
標準庫 strings 包中有一個函數(shù) FieldsFunc 可以指定多個字符為分隔符。
ss := strings.FieldsFunc(s,f func(rune) bool)
示例:
package main
import (
?? ?"fmt"
?? ?"strings"
?? ?"unicode"
)
func main() {
?? ?f := func(c rune) bool {
?? ??? ?return !unicode.IsLetter(c) && !unicode.IsNumber(c)
?? ?}
?? ?fmt.Printf("Fields are: %q", strings.FieldsFunc(" ?foo1;bar2,baz3...", f))
}輸出:
Fields are: ["foo1" "bar2" "baz3"]
4.按多個字符串分割
截至 Go 1.20,標準庫暫未供支持多個字符串作為分隔符的分割函數(shù)。但是,我們可以基于 strings.Split 編寫一個函數(shù)來實現(xiàn)這個功能。
// SplitSeps splits string into substring slice by multiple string separators.
// If you want to specify multiple string separators by regexp,
// please refer to `func (*Regexp) Split` in standard library regexp package.
func SplitSeps(s string, seps ...string) []string {
?? ?if len(seps) == 0 {
?? ??? ?return []string{s}
?? ?}
?? ?result := strings.Split(s, seps[0])
?? ?for _, sep := range seps[1:] {
?? ??? ?var temp []string
?? ??? ?for _, r := range result {
?? ??? ??? ?temp = append(temp, strings.Split(r, sep)...)
?? ??? ?}
?? ??? ?result = temp
?? ?}
?? ?return result
}示例:
package main
import (
?? ?"fmt"
?? ?"strings"
)
func main() {
?? ?fmt.Printf("%q\n", SplitSeps("foo,bar,baz", []string{","}...))
?? ?fmt.Printf("%q\n", SplitSeps("foo,bar|baz", []string{",", "|"}...))
?? ?fmt.Printf("%q\n", SplitSeps("foo,bar|baz qux", []string{",", "|", " "}...))
?? ?fmt.Printf("%q\n", SplitSeps("foo,bar|bazSEPqux", []string{",", "|", "SEP"}...))
?? ?fmt.Printf("%q\n", SplitSeps("foo,bar|baz", []string{}...))
?? ?fmt.Printf("%q\n", SplitSeps(" xyz", []string{""}...))
}輸出:
["foo" "bar" "baz"]
["foo" "bar" "baz"]
["foo" "bar" "baz" "qux"]
["foo" "bar" "baz" "qux"]
["foo,bar|baz"]
[" " "x" "y" "z"]
5.其他分割函數(shù)
除了文中提及的標準庫函數(shù),你可能還會用到下面這幾個函數(shù)來控制字符串的分割方式。
strings.SplitN
func strings.SplitN(s, sep string, n int) []string
該函數(shù)與 Split 函數(shù)類似,但是可以指定分割后的最大子字符串個數(shù) n,如果 n 為正數(shù),則最多分割成 n 個子字符串;如果 n 為負數(shù),則不限制子字符串個數(shù)。例如:
str := "hello,world,how,are,you" words := strings.SplitN(str, ",", 2) fmt.Println(words) // ["hello", "world,how,are,you"]
strings.SplitAfter
func SplitAfter(s, sep string) []string
該函數(shù)將字符串 s 按照分割符 sep 分割成多個子字符串,并返回一個字符串切片。不同于 Split 函數(shù)的是,SplitAfter 函數(shù)會在分割符之后分割,例如:
str := "hello,world,how,are,you" words := strings.SplitAfter(str, ",") fmt.Println(words) // ["hello,", "world,", "how,", "are,", "you"]
strings.SplitAfterN
func SplitAfterN(s, sep string, n int) []string
該函數(shù)與 SplitAfter 函數(shù)類似,但是可以指定分割后的最大子字符串個數(shù) n。如果 n 為負數(shù),則不限制子字符串個數(shù)。例如:
str := "hello,world,how,are,you" words := strings.SplitAfterN(str, ",", 2) fmt.Println(words) // ["hello,", "world,how,are,you"]
6.go-huge-util
借助 Golang 標準庫提供的相關函數(shù),分割字符串還是比較方便的。
文中提及的兩個函數(shù),已放置 Github 開源工具庫 go-huge-util,大家可使用 go mod 方式 import 然后使用。
import "github.com/dablelv/go-huge-util/str" // Split 如果待分割串為空串,返回 nil 切片而非包含一個空串的切片。 str.Split(s, sep string) []string // SplitSeps 通過多個字符串分隔符將字符串分割為字符串切片。 str.SplitSeps(s string, seps []string) []string
go-huge-util 除了類型轉換,還有很多其他實用函數(shù),如加解密、zip 解壓縮等,歡迎大家使用、Star、Issue 和 Pull Request。
參考文獻
strings - Go Packages
8 ways to split a string in Go (Golang) - GOSAMPLES
github.com/dablelv/go-huge-util
到此這篇關于Golang 分割字符串的實現(xiàn)示例的文章就介紹到這了,更多相關Golang 分割字符串內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
一篇文章讀懂Golang?init函數(shù)執(zhí)行順序
init()函數(shù)會在包被初始化后自動執(zhí)行,并且在main()函數(shù)之前執(zhí)行,但是需要注意的是init()以及main()函數(shù)都是無法被顯式調用的,下面這篇文章主要給大家介紹了關于如何通過一篇文章讀懂Golang?init函數(shù)執(zhí)行順序的相關資料,需要的朋友可以參考下2022-11-11

