- C 标准库
- C 库 - 首页
- C 库 - <assert.h>
- C 库 - <complex.h>
- C 库 - <ctype.h>
- C 库 - <errno.h>
- C 库 - <fenv.h>
- C 库 - <float.h>
- C 库 - <inttypes.h>
- C 库 - <iso646.h>
- C 库 - <limits.h>
- C 库 - <locale.h>
- C 库 - <math.h>
- C 库 - <setjmp.h>
- C 库 - <signal.h>
- C 库 - <stdalign.h>
- C 库 - <stdarg.h>
- C 库 - <stdbool.h>
- C 库 - <stddef.h>
- C 库 - <stdio.h>
- C 库 - <stdlib.h>
- C 库 - <string.h>
- C 库 - <tgmath.h>
- C 库 - <time.h>
- C 库 - <wctype.h>
- C 标准库资源
- C 库 - 快速指南
- C 库 - 有用资源
- C 库 - 讨论
C 库函数 - strlen()
C 库 strlen() 函数用于计算字符串的长度。此函数不计算空字符 '\0'。
在此函数中,我们传递指向要确定其长度的字符串的第一个字符的指针,并作为结果返回字符串的长度。
语法
以下是 C 库 strlen() 函数的语法:
size_t strlen(const char *str)
参数
此函数仅接受一个参数:
str - 这是要查找其长度的字符串。
返回值
此函数返回字符串的长度。
示例 1
以下是说明给定字符串以使用 strlen() 函数查找长度的 C 库程序。
#include <stdio.h>
#include <string.h>
int main() {
char len[] = "Tutorialspoint";
printf("The length of given string = %d", strlen(len));
return 0;
}
输出
执行上述代码后,我们将得到以下结果:
The length of given string = 14
示例 2
这里,我们使用两个函数 - strcpy() 通过复制第二个参数创建第一个字符串。然后我们借助 strlen() 计算字符串的长度。
#include <stdio.h>
#include >string.h>
int main () {
char str[50];
int len;
strcpy(str, "This is tutorialspoint");
len = strlen(str);
printf("Length of |%s| is |%d|\n", str, len);
return(0);
}
输出
执行代码后,我们将得到以下结果:
Length of |This is tutorialspoint| is |22|
示例 3
下面的示例演示了在循环迭代中使用 strlen() 函数来获取给定指定字符的计数。
#include<stdio.h>
#include<string.h>
int main()
{
int i, cnt;
char x[] = "Welcome to Hello World";
cnt = 0;
for(i = 0; i < strlen(x); i++)
{
if(x[i] == 'e')
cnt++;
}
printf("The number of e's in %s is %d\n", x, cnt);
return 0;
}
输出
以上代码产生以下结果:
The number of e's in Welcome to Hello World is 3
广告