Golang – strings.SplitN()


strings.SplitN() 是 Go 语言中用于通过给定分隔符对给定字符串拆分成子字符串的内置函数。它返回这些分隔符之间的子字符串的切片。

语法

func SplitN(str, sep string, n int) []string

其中:

  • str 是给定的输入字符串,
  • sep 是分隔符字符串,
  • n 定义要返回的子字符串数。

示例 1

考虑以下示例 −

package main
import (
   "fmt"
   "strings"
)
func main() {
   // Intializing the Strings
   p := "1, 2, 3, 4, 5, 6, 7"
   q := "Welcome to Golang Programming Language"
   r := "SplitN"
   s := "1.2.3.4.5"
   t := "String/Package/Function"

   // Display the Strings
   fmt.Println("String 1: ", p)
   fmt.Println("String 2: ", q)
   fmt.Println("String 3: ", r)
   fmt.Println("String 4: ", s)
   fmt.Println("String 5: ", t)

   // Using the SplitN Function
   test1 := strings.SplitN(p, ",", 6)
   test2 := strings.SplitN(q, " ", 0)
   test3 := strings.SplitN(r, "N", -1)
   test4 := strings.SplitN(s, ".", 5)
   test5 := strings.SplitN(t, "/", 3)
   test6 := strings.SplitN(q, "to ", -1)
   test7 := strings.SplitN(s, ".", 4)
   
   // Display the SplitN Output
   fmt.Println("\nSplitN for String 1:", test1)
   fmt.Println("SplitN for String 2:", test2)
   fmt.Println("SplitN for String 3:", test3)
   fmt.Println("SplitN for String 4:", test4)
   fmt.Println("SplitN for String 5:", test5)
   fmt.Println("SplitN for String 2:", test6)
   fmt.Println("SplitN for String 4:", test7)
}

输出

它将生成以下输出 −

String 1: 1, 2, 3, 4, 5, 6, 7
String 2: Welcome to Golang Programming Language
String 3: SplitN
String 4: 1.2.3.4.5
String 5: String/Package/Function

SplitN for String 1: [1 2 3 4 5 6, 7]
SplitN for String 2: []
SplitN for String 3: [Split ]
SplitN for String 4: [1 2 3 4 5]
SplitN for String 5: [String Package Function]
SplitN for String 2: [Welcome Golang Programming Language]
SplitN for String 4: [1 2 3 4.5]

示例 2

我们再举一个例子。

package main
import (
   "fmt"
   "strings"
)
func main() {

   // Declaring the Variables
   var x string
   var y string
   
   // Intializing the Strings
   x = "Golang Programming Language"
   y = "SplitN-String-Package-Function"
   
   // Display the Strings
   fmt.Println("String 1: ", x)
   fmt.Println("String 2:", y)

   // Using SplitN
   z := strings.SplitN(x, "Programming", 2)
   w := strings.SplitN(y, "-", 3)
   
   // Display the SplitN Output
   fmt.Println("SplitN for String 1:", z)

   // Using the for condition to display outputs of y variable
   for v := range(w) {
      fmt.Println("SplitN Function for String 2: ", w[v])
   }
}

输出

它将生成以下输出 −

String 1: Golang Programming Language
String 2: SplitN-String-Package-Function
SplitN for String 1: [Golang Language]
SplitN Function for String 2: SplitN
SplitN Function for String 2: String
SplitN Function for String 2: Package-Function

更新于: 10-Mar-2022

776 次查看

开启您的 职业

完成课程,获得认证

开始学习
广告