package main标签:index,string,fmt,空格,字符串,Go,tmpstr,spc From: https://blog.51cto.com/u_15828115/5753999
import (
"fmt"
"regexp"
)
func main() {
oldstr := "I have a dream"
fmt.Println(oldstr)
newstr := DeleteExtraSpace(oldstr)
fmt.Println(newstr)
}
//删除字符串中的多余空格,有多个空格时,仅保留一个空格
func DeleteExtraSpace(s string) string {
regstr := "\\s{2,}"
reg, _ := regexp.Compile(regstr)
tmpstr := make([]byte, len(s))
copy(tmpstr, s)
spc_index := reg.FindStringIndex(string(tmpstr))
for len(spc_index) > 0 {
tmpstr = append(tmpstr[:spc_index[0]+1], tmpstr[spc_index[1]:]...)
spc_index = reg.FindStringIndex(string(tmpstr))
}
return string(tmpstr)
}