package main
import (
"fmt"
"strings"
)
func main() {
stringOne := "merpflakes"
stringTwo := " "
stringThree := ""
if len(strings.TrimSpace(stringOne)) == 0 {
fmt.Println("String is empty!")
}
if len(strings.TrimSpace(stringTwo)) == 0 {
fmt.Println("String two is empty!")
}
if len(stringTwo) == 0 {
fmt.Println("String two is still empty!")
}
if len(strings.TrimSpace(stringThree)) == 0 {
fmt.Println("String three is empty!")
}
}
269
假设应删除空格和所有前导和尾随空格:
import "strings"
if len(strings.TrimSpace(s)) == 0 { ... }
因为: len("") // is 0 len(" ") // one empty space is 1 len(" ") // two empty spaces is 2
// Strempty checks whether string contains only whitespace or not
func Strempty(s string) bool {
if len(s) == 0 {
return true
}
r := []rune(s)
l := len(r)
for l > 0 {
l--
if !unicode.IsSpace(r[l]) {
return false
}
}
return true
}
7 回答
两种样式都在Go的标准库中使用 .
可以在
strconv
包中找到:http://golang.org/src/pkg/strconv/atoi.go可以在
encoding/json
包中找到:http://golang.org/src/pkg/encoding/json/encode.go两者都是惯用的,并且足够清晰 . 这更多的是个人品味和清晰度 .
Russ Cox写道golang-nuts thread:
这似乎是过早的微观优化 . 编译器可以自由地为两种情况生成相同的代码,或至少为这两种情况生成相同的代码
和
因为语义明显相等 .
检查长度是一个很好的答案,但您也可以考虑一个“空”字符串,它也只是空格 . 不是“技术上”空的,但如果你想检查:
假设应删除空格和所有前导和尾随空格:
因为:
len("") // is 0
len(" ") // one empty space is 1
len(" ") // two empty spaces is 2
截至目前,Go编译器在两种情况下都生成相同的代码,因此这是一个品味问题 . GCCGo会生成不同的代码,但几乎没有人使用它,所以我不担心 .
https://godbolt.org/z/fib1x1
使用类似下面的函数会更干净,更不容易出错:
这比修剪整个字符串更有效,因为您只需检查至少一个非空格字符