Method of splitting strings with variable number of spaces in Golang

There is such a scenario where spaces are used to split strings. The number of spaces between the divided substrings in the string is uncertain. There are one or two or more spaces. In this scenario, use the strings.Split function that is easiest to think of Just can't do it. This article then introduces several effective methods.

Using the strings.Fields function

The strings.Fields function accepts a parameter of string type, uses spaces and multiple consecutive spaces to split the string, and returns a string slice, which just meets our needs. An example of use is as follows:

package main

import (
	"fmt"
	"strings"
)

func main() {
	str := "欢迎来到路多辛的博客 所思所想          很棒"
	s := strings.Fields(str)
	fmt.Println(s)
}

Run to see the effect:

$ go run main.go
[欢迎来到路多辛的博客 所思所想 很棒]

It can be seen that although the substrings in str are separated by different numbers of spaces, a slice of string type is obtained after processing with the strings.Fields function, and the string is perfectly divided.

use regular expressions

First look at the sample code:

package main

import (
	"fmt"
	"regexp"
)

func main() {
	str := "欢迎来到路多辛的博客 所思所想          很棒"
	reg := regexp.MustCompile(`\s+`)
	result := reg.Split(str, -1)
	fmt.Println(result)
}

Run to see the effect:

$ go run main.go
[欢迎来到路多辛的博客 所思所想 很棒]

Get the same data as the previous example, first use the regexp.MustCompile function to create a regular expression to match one or more spaces (\s+ means to match at least one space character). Then use the reg.Split method to split the string, and the second parameter -1 means to return all substrings.

Guess you like

Origin blog.csdn.net/luduoyuan/article/details/131905787