C语言 strlen 函数用来求字符串的长度(包含多少个字符)。
strlen() 函数从字符串的开头位置依次向后计数,直到遇见\0
,然后返回计时器的值。最终统计的字符串长度不包括\0
。
头文件:string.h
示例1
#include <stdio.h>
#include <string.h>
void main()
{
char s[] = "apple";
printf("%d\n",strlen(s));
}
结果:
因为C语言在字符串后面会默认加一个‘\0’,所以这次计数是5(strlen不计\0)
示例2:
#include <stdio.h>
#include <string.h>
void main()
{
char s[] = {'a','b','\0','c'};
printf("%d\n",strlen(s));
}
结果:
因为计数是从头开始直到遇到\0,所以在这个数组中尽管\0后面还有字符,但不会进行计数。