Golang 在指定的分隔符之后分割字符串

Golang 在指定的分隔符之后分割字符串

在Go语言中,字符串与其他语言如Java、C++、Python等不同。它是一个宽度可变的字符序列,每一个字符都由一个或多个使用UTF-8编码的字节表示。

在Go语言的字符串中,你可以使用 SplitN() 函数在指定的分隔符之后分割字符串。这个函数将一个片断分割成给定分隔符的每个实例之后的所有子串,并返回这些分隔符之间的子串片断。count表示要返回的子片的数量。它被定义在字符串包中,因此,你必须在你的程序中导入字符串包以访问SplitN函数。

语法

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

这里, str 是字符串, sep 是分隔符。如果str不包含给定的sep并且sep不是空的,那么它将返回一个长度为1的片断,其中只包含str。或者如果sep是空的,那么它将在每个UTF-8序列之后进行分割。或者,如果str和sep都是空的,那么它将返回一个空的片段。

例1 :

// Go program to illustrate the concept
// of splitting a string
package main
  
import (
    "fmt"
    "strings"
)
  
func main() {
  
    // Creating and Splitting a string
    // Using SplitN function
    res1 := strings.SplitN("****Welcome, to, GeeksforGeeks****", ",", -1)
  
    res2 := strings.SplitN("Learning x how x to x trim"+
                       " x a x slice of bytes", "x", 3)
  
    res3 := strings.SplitN("Geeks,for,Geeks, Geek", ",", 0)
  
    res4 := strings.SplitN("", ",", 2)
  
    // Display the results
    fmt.Printf("\nFinal Result after splitting:\n")
    fmt.Printf("\nSlice 1: %s", res1)
    fmt.Printf("\nSlice 2: %s", res2)
    fmt.Printf("\nSlice 3: %s", res3)
    fmt.Printf("\nSlice 4: %s", res4)
}

输出

Final Result after splitting:

Slice 1: [****Welcome  to  GeeksforGeeks****]
Slice 2: [Learning   how   to x trim x a x slice of bytes]
Slice 3: []
Slice 4: []

例2 :

// Go program to illustrate the concept
// of splitting the string
package main
  
import (
    "fmt"
    "strings"
)
  
func main() {
  
    // Creating and initializing a string
    // Using shorthand declaration
    string_1 := "Welcome, to, Geeks, for, Geeks"
    string_2 := "AppleAppleAppleAppleAppleApple"
    string_3 := "%G%E%E%K%sS"
  
    // Displaying strings
    fmt.Println("Original Strings:")
    fmt.Printf("String 1: %s", string_1)
    fmt.Printf("\nString 2: %s", string_2)
    fmt.Printf("\nString 3: %s", string_3)
  
    // Splitting the given strings
    // Using SplitN function
    res1 := strings.SplitN(string_1, ",", 2)
    res2 := strings.SplitN(string_2, "pp", 3)
    res3 := strings.SplitN(string_3, "%", 0)
  
    // Display the results
    fmt.Printf("\n\nAfter splitting:\n")
    fmt.Printf("\nString 1: %s", res1)
    fmt.Printf("\nString 2: %s", res2)
    fmt.Printf("\nString 3: %s", res3)
  
}

输出

Original Strings:
String 1: Welcome, to, Geeks, for, Geeks
String 2: AppleAppleAppleAppleAppleApple
String 3: %G%E%E%K%sS

After splitting:

String 1: [Welcome  to, Geeks, for, Geeks]
String 2: [A leA leAppleAppleAppleApple]
String 3: []

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程