Go 语言中的 strings.Split() 函数


strings.Split() 用于使用指定的定界符将字符串分解为一个子串列表。它以切片形式返回子串。

语法

strings.Split() 的语法如下所示 −

func Split(S string, sep string) []string

其中 s 是给定的字符串,sep 是定界符(分隔符)字符串。它返回子串。

例 1

让我们考虑以下示例 −

package main
import (
   "fmt"
   "strings"
   "regexp"
)
func main() {
   // Intializing the Strings
   p := "oopsfunctions"
   q := "GoLang language"

   // Display the Strings
   fmt.Println("String 1:", p)
   fmt.Println("String 2:", q)

   // Using the Split Function and regexp
   r := regexp.MustCompile(`[ns]`)
   s := r.Split(p, -2)
   t := strings.Split(q, "Lang")
   u := strings.Split(p, "")

   // Display the Split Output
   fmt.Println("Split String 1: ", s)
   fmt.Println("Split String 2: ", t)
   fmt.Println("Split String 1 with delimiter:", u)
}

输出

它将生成以下输出 −

String 1: oopsfunctions
String 2: GoLang language
Split String 1: [oop fu ctio ]
Split String 2: [Go language]
Split String 1 with delimiter: [o o p s f u n c t i o n s]

例 2

我们再举一个例子。

package main
import (
   "fmt"
   "strings"
)
func main() {
   var x string
   var y string
   var w string

   // Intializing the Strings
   x = "Hello! World"
   y = "This, is, a, sample, program"
   w = "1-2-3-4"

   // Display the Strings
   fmt.Println("String 1:", x)
   fmt.Println("String 2:", y)
   fmt.Println("String 3:", w)

   // Using the Split Function
   res1 := strings.Split(x, "!")
   res2 := strings.Split(y, ",")
   res3 := strings.Split(w, "-")
   res4 := strings.Split(y, "a")

   // Display the Split Output
   fmt.Println("Split String 1:", res1)
   fmt.Println("Split String 2:", res2)
   fmt.Println("Split String 3:", res3)
   fmt.Println("Split String 2 with delimiter:", res4)
}

输出

它将生成以下输出 −

String 1: Hello! World
String 2: This, is, a, sample, program
String 3: 1-2-3-4
Split String 1: [Hello World]
Split String 2: [This is a sample program]
Split String 3: [1 2 3 4]
Split String 2 with delimiter: [This, is, , s mple, progr m]

更新时间: 2022 年 3 月 10 日

7K+ 浏览量

开启你的 职业生涯

完成课程,获得认证

立即开始
广告
© . All rights reserved.