Use the function
The function accepts a string-type parameter, uses spaces and multiple consecutive spaces to split the string, and returns a string slice, which just meets our needs. Examples of use are as follows:
package main import ( "fmt" "strings" ) func main() { str := "Welcome to Ludosin's blog What Is Great" s := (str) (s) }
Run to see the effect:
$ go run
[Welcome to Ludosin's blog What I think is great]
It can be seen that although the substrings in str are separated by spaces of varying numbers, a slice of string type is obtained after processing using the function, and the string is perfectly divided.
Using regular expressions
First look at the sample code:
package main import ( "fmt" "regexp" ) func main() { str := "Welcome to Ludosin's blog What Is Great" reg := (`\s+`) result := (str, -1) (result) }
Run to see the effect:
$ go run
[Welcome to Ludosin's blog What I think is great]
Get the same data as in the previous example, first use the function to create a regular expression to match one or more spaces (\s+ means to match at least one space character). Then use the method to split the string, and the second parameter -1 means that all substrings are returned.
This is the end of this article about how to split strings using uncertain number of spaces in Golang. For more related content of spaces in Golang, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!