比较是否为假,因为已为字符串设置了 strBytes 的字节大小?
str := "test"
strBytes := make([]byte, 10)
copy(strBytes[:], str)
str1 := strings.TrimSpace(string(strBytes))
//why is this comparison false even though the string object is same => "test"
compare := str == str1
fmt.Printf("%v == %v = %v", str, str1, compare)
Go playground link
最佳答案
string(strBytes)
与str
不同,因为它包含不可打印的符文。您可以使用 unicode.IsPrint
method检查符文是否可打印。 Here是在strBytes
中显示不可打印符文的代码:
import (
"fmt"
"unicode"
"unicode/utf8"
)
func main() {
str := "test"
strBytes := make([]byte, 8)
copy(strBytes[:], str)
for len(strBytes) > 0 {
r, size := utf8.DecodeRune(strBytes)
fmt.Printf("Char: %q; Printable: %v\n", r, unicode.IsPrint(r))
strBytes = strBytes[size:]
}
}