strlen 在 C 语言中的作用
strlen函数是一个 C 语言库函数,用于获取字符串的长度,即字符串中字符的数量(不包括终止符 '\0')。
作用原理:
strlen函数遍历字符串,直到遇到终止符 '\0'。它通过计算从字符串起始位置到终止符位置的字符数来确定字符串的长度。
立即学习“C语言免费学习笔记(深入)”;
函数原型:
<code class="C">size_t strlen(const char *str);</code>
参数:
str:指向要计算长度的字符串的指针。
返回值:
strlen函数返回字符串的长度(类型为
size_t)。
示例用法:
<code class="C">#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello World";
size_t len = strlen(str);
printf("The length of the string '%s' is: %d\n", str, len);
return 0;
}</code>输出:
<code>The length of the string 'Hello World' is: 11</code>
注意:
strlen函数不修改原始字符串。 它返回字符串的字节长度,而不是 Unicode 编码的字符长度。 如果字符串为
NULL,
strlen函数返回 0。
