在Go中,要删除字符串中的重复白位,可以使用 strings.Fields()函数将字符串围绕一个或多个空白字符进行分割,然后用一个空格分隔符连接子字符串的片断。 strings.Join()与一个空格分隔符连接。或者,你可以使用正则表达式来寻找重复的空白字符,并使用 ReplaceAllString()的方法来替换它们。 regexp包中的方法。
移除重复的空白字符,使用 strings.Fields()函数
package main
import (
"fmt"
"strings"
)
func main() {
s := "GOSAMPLES.dev is \t \r\n the best Golang \t\t\t\t website in the \n world!"
res := strings.Join(strings.Fields(s), " ")
fmt.Println(res)
}
在这个方法中,我们做两件事:
- 我们使用函数将一个或多个空白字符周围的字符串分割开来。
strings.Fields()函数对字符串进行分割。空白字符的定义是unicode.IsSpace(),包括'\t','\n','\r',' ',等等。结果,我们得到了片断。
[]string{"GOSAMPLES.dev", "is", "the", "best", "Golang", "website", "in", "the", "world!"}
- 我们使用函数将子字符串的片断连接起来。
strings.Join()函数,用一个空格" "作为分隔符。这样,我们构建的结果字符串中,所有重复的白位都被去除。
使用正则表达式删除重复的空白处
package main
import (
"fmt"
"regexp"
)
func main() {
s := "GOSAMPLES.dev is \t \r\n the best Golang \t\t\t\t website in the \n world!"
pattern := regexp.MustCompile(`\s+`)
res := pattern.ReplaceAllString(s, " ")
fmt.Println(res)
}
使用正则表达式,我们可以达到与前一种方法相同的效果。我们定义\s+ 模式,至少匹配一个空白字符([ \t\r\n\f]),然后用一个空格替换该表达式的所有出现,得到去除重复空白的字符串。
这两种方法产生的结果是一样的,即:
GOSAMPLES.dev is the best Golang website in the world!