C++ 是字符空终止符包含在长度计数中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14905937/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
is that char null terminator is including in the length count
提问by runcode
#include <stdio.h>
int main(int argc, char *argv[]) {
char s[]="help";
printf("%d",strlen(s));
}
Why the above output is 4, isnt that 5 is the correct answer?
为什么上面的输出是4,那5不是正确答案吗?
it should be 'h','e','l','p','\0' in memory..
它应该是 'h','e','l','p','\0' 在内存中..
Thanks.
谢谢。
回答by billz
strlen
: Returns the length of the given byte string not including null terminator;
strlen
: 返回给定字节串的长度,不包括空终止符;
char s[]="help";
strlen(s) should return 4.
sizeof
: Returns the length of the given byte string, include null terminator;
sizeof
: 返回给定字节串的长度,包括空终止符;
char s[]="help";
sizeof(s) should return 5.
回答by 0x499602D2
strlen
counts the elements until it reaches the null character, in which case it will stop counting. It won't include it with the length.
strlen
对元素进行计数直到到达空字符,在这种情况下它将停止计数。它不会包括它的长度。
回答by Chris Hartman
strlen()
does not count the number of characters in the array (in fact, this might not even be knowable (if you only have a pointer to the memory, instead of an array). It does, as you have found out, count the number of characters up to but not including the null character. Consider char s[] = {'h','i','\0','t','h','e','r','e'};
strlen()
不计算数组中的字符数(实际上,这甚至可能不可知(如果您只有一个指向内存的指针,而不是数组)。正如您所发现的,它确实计算了字符直到但不包括空字符。考虑 char s[] = {'h','i','\0','t','h','e','r','e'};
回答by phoeagon
strlen(const char* ptr)
returns the length of the string by counting the non-zero elements starting at until reaches zero. So '\0'
doesn't count.
strlen(const char* ptr)
通过计算从 开始直到达到零的非零元素来返回字符串的长度。所以'\0'
不算。
I recommend that you consult the reference like linkfor questions like this.
对于此类问题,我建议您参考类似链接的参考资料。
It's clearly stated as:
它明确表示为:
A C string is as long as the number of characters between the beginning
of the string and the terminating null character (without including the
terminating null character itself).
回答by nos
It's 4.
是 4。
strlen() counts the number of characters up to, but not including, the first char with a value of 0 - the nul terminator.
strlen() 计算最多但不包括值为 0 的第一个字符 - nul 终止符的字符数。