2 回答
TA贡献1802条经验 获得超6个赞
您不为字符串文字编写字符串长度或空终止字符这一事实并不意味着它不能自动完成:编译器可以做到(因为它在编译时知道字符串长度)并且很可能正在做它。
例如在C中:
空字符('\0'、L'\0'、char16_t() 等)始终附加到字符串文字:因此,字符串文字“Hello”是包含字符“H”的 const char[6] 、'e'、'l'、'l'、'o' 和 '\0'。
这是一个小型 C 程序,显示空字符附加到字符串文字:
#include <stdio.h>
#include <string.h>
int main()
{
char *p="hello";
int i;
i = 0;
while (p[i] != '\0')
{
printf("%c ", p[i]);
i++;
}
printf("\nstrlen(p)=%ld\n", strlen(p));
return 0;
}
执行:
./hello
h e l l o
strlen(p)=5
您还可以使用以下命令在调试模式下编译程序:
gcc -g -o hello -Wall -pedantic -Wextra hello.c
并检查gdb:
gdb hello
...
(gdb) b main
Breakpoint 1 at 0x400585: file hello.c, line 6.
(gdb) r
Starting program: /home/pifor/c/hello
Breakpoint 1, main () at hello.c:6
6 char *p="hello";
(gdb) n
9 i = 0;
(gdb) print *(p+5)
$7 = 0 '\000'
(gdb) print *(p+4)
$8 = 111 'o'
(gdb) print *p
$10 = 104 'h'
TA贡献1786条经验 获得超11个赞
Go 中的字符串值是指向字节和长度的指针。这是Go 对 type 的定义:
type StringHeader struct {
Data uintptr
Len int
}
对于类似 的字符串文字"world",编译器会计算字节数以设置长度。StringHeader{Data: pointerToBytesWorld, Len: 5}文字在运行时由 表示 。
长度通过切片表达式隐含在字符串值的切片操作数中:
s := "Hello"
s = s[1:4] // length is 4 - 1 = 3
字符串转换取操作数的长度:
b := []byte{'F', 'o', 'p'}
s = string(b) // length is 3, same as len(b)
- 2 回答
- 0 关注
- 158 浏览
添加回答
举报
