人間四月芳菲盡,山寺桃花始盛開。歲月不居,時節如流,年過,瞬至四月,猶一日也。
函數:
func DeletePreAndSufSpace(str string) string {
strList := []byte(str)
spaceCount, count := 0, len(strList)
for i := 0; i <= len(strList)-1; i++ {
if strList[i] == 32 {
spaceCount++
} else {
break
}
}
strList = strList[spaceCount:]
spaceCount, count = 0, len(strList)
for i := count - 1; i >= 0; i-- {
if strList[i] == 32 {
spaceCount++
} else {
break
}
}
return string(strList[:count-spaceCount])
}
test:
func main() {
s1 := " a a a "
fmt.Println("原:", s1) // a a a
fmt.Println(DeletePreAndSufSpace(s1)) //a a a
s2 := " 和 a 和 "
fmt.Println("原:", s2) // 和 a 和
fmt.Println(DeletePreAndSufSpace(s2)) //和 a 和
s3 := " " //都是空格時全部消除
fmt.Println("原:", s3) //
fmt.Println(DeletePreAndSufSpace(s3)) //
}
如果解決了你的問題,可以點個贊哦!再會!