c语言中strlen函数的作用
strlen函数是一个C语言标准库函数,用于计算给定字符串的长度。它返回字符串中字符的数量(不包括终止空字符'\0')。
用法
strlen函数的语法如下:
立即学习“C语言免费学习笔记(深入)”;
<code class="c">size_t strlen(const char *str);</code>
其中,
str:要计算长度的字符串。它是一个指向字符数组的指针。返回值
strlen函数返回类型为size_t,表示无符号整数类型,它包含字符串的长度。
示例
以下示例演示了strlen函数的用法:
<code class="c">#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, world!";
int len;
// 计算字符串的长度
len = strlen(str);
// 输出字符串的长度
printf("字符串 '%s' 的长度为:%d\n", str, len);
return 0;
}</code>输出:
<code>字符串 'Hello, world!' 的长度为:13</code>
注意:
strlen函数只计算字符串中字符的数量,不包括终止空字符'\0'。 如果传递给strlen函数的字符串为NULL,它将返回0。 strlen函数在C语言标准库中定义,因此在使用它之前需要包含头文件<string.h></string.h>。
