温馨提示×

C语言的strlen函数怎么使用

小亿
107
2023-06-25 11:39:26
栏目: 编程语言

strlen函数用于计算字符串的长度,其语法如下:

size_t strlen(const char *s);

其中,参数s是一个指向以null结尾的字符串的指针。函数返回值是字符串s的长度,不包括null字符。

使用示例:

#include <stdio.h>
#include <string.h>
int main() {
char str[] = "hello world";
size_t len = strlen(str);
printf("The length of the string is %zu\n", len);
return 0;
}

输出结果为:

The length of the string is 11

注意,字符串必须以null字符结尾,否则strlen函数会继续计算字符串长度,直到遇到null字符为止。如果字符串没有null字符,那么strlen函数的行为是未定义的。

0