Use the strings.SplitAfter function to split a string into multiple substrings according to the specified suffix
In the strings package of Go language, there is a very useful function strings.SplitAfter that can split a string into multiple substrings according to the specified suffix. The suffix is separated into multiple substrings. The use of this function is very simple. You only need to pass in the string to be split and the suffix, and you will get a slice in which each element is a substring.
Below I will demonstrate the specific usage of the strings.SplitAfter function and illustrate it more intuitively through a code example.
package main import ( "fmt" "strings" ) func main() { str := "Hello,World!-Hello,Go!-Hello,Program!" substr := "-" result := strings.SplitAfter(str, substr) fmt.Println(result) }
Run the above code, the output will be a string slice, which contains substrings separated by the specified suffix:
[Hello,World!- Hello,Go!- Hello,Program!]
As you can see, the string str
was successfully separated into three substrings according to the specified suffix -
.
It should be noted that when using the strings.SplitAfter function to split, the function will keep the specified suffix at the end of the substring. Therefore, if a suffix appears at the end of a string, it will be added to the end of each substring, even if the suffix was already present at the end of the previous substring.
In addition, if you need to customize the delimiter, you can use string slicing through strings.SplitAfter. For example, you can use "," to separate strings:
package main import ( "fmt" "strings" ) func main() { str := "Hello,World!-Hello,Go!-Hello,Program!" substr := "," result := strings.SplitAfter(str, substr) fmt.Println(result) }
The output will be a string slice containing substrings separated by the specified suffix ,
:
[Hello, World!, Hello, Go!, Hello, Program!]
It can be seen that the string str
was successfully divided into three substrings according to the specified suffix ,
.
To sum up, by using the SplitAfter function in the strings package of Go language, we can easily separate a string into multiple substrings according to the specified suffix. The use of this function is very simple. You only need to pass in the string to be split and the suffix, and you will get a slice in which each element is a substring. This is useful when working with strings that need to be split by a specified suffix.
The above is the detailed content of Use the strings.SplitAfter function to split a string into multiple substrings according to the specified suffix.. For more information, please follow other related articles on the PHP Chinese website!