Golang去除字符串前后空格
实现Demo
package main
import "fmt"
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])
}
func main() {
str := " 1111 "
s := DeletePreAndSufSpace(str)
fmt.Println(len(s))
}
输出
4
UPDATE AT 2020-5-19 09:31:42
可以直接使用strings包提供的函数
实现Demo
func main() {
str := " 1111 "
s := strings.Trim(str," ")
fmt.Println(len(s))
}
输出:
4