注意:这里要区分
0
,
'\0'
,
'0'
的区别。其中前两者等价,是内存中实际的值。而
'0'
是显示的值,其在内存中实际是
48
,也即
0x30
'\0'0
#include <stdio.h>
#include <string.h>
int main() {
char s[] = {'a', 'b', 'c', '\0', '\0', 'd'};
printf("%d %d %s\n", strlen(s), sizeof(s), s);
return 0;
}
3 6 abc
0
package main
import (
"fmt"
)
func main() {
b := []byte{'a', 'b', 'c', 0, 0, 'd'}
s := string(b)
fmt.Printf("%d %s %s\n", len(s), s, b)
}
6 abcd abcd
0io.Reader(b []byte)b0string(b)[]bytestring
00
// String 将 `[]byte` 转换为 `string`
func String(b []byte) string {
for idx, c := range b {
if c == 0 {
return string(b[:idx])
}
}
return string(b)
}
// StringWithoutZero 将 `[]byte` 转换为 `string`
func StringWithoutZero(b []byte) string {
s := make([]rune, len(b))
offset := 0
for i, c := range b {
if c == 0 {
offset++
} else {
s[i-offset] = rune(c)
}
}
return string(s[:len(b)-offset-1])
}