人间四月芳菲尽,山寺桃花始盛开。岁月不居,时节如流,年过,瞬至四月,犹一日也。
函数:
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)) //
}
如果解决了你的问题,可以点个赞哦!再会!