Home > Common Problem > body text

How to calculate the length of string in C language

步履不停
Release: 2019-07-06 10:01:36
Original
46509 people have browsed it

How to calculate the length of string in C language

C语言计算字符串长度,可以手动计算也可以使用库函数或者sizeof()操作符。

方法:

自定义函数求长度

使用strlen()函数

使用sizeof()操作符

自定义函数:

How to calculate the length of string in C language

int cont_str(char *s)
{
int i = 0;      
while ( str[i++] != '\0')   ;
return i;
}
Copy after login

使用string头文件中的strlen()函数:

How to calculate the length of string in C language

strlen(str); //假设str为待求的字符串数组名

使用sizeof()操作符:

How to calculate the length of string in C language

sizeof(str)/sizeof(str[0]); //假设str为待求的字符串数组名

注意:

strlen()函数求出的字符串长度为有效长度,既不包含字符串末尾结束符 ‘\0’;

sizeof()操作符求出的长度包含字符串末尾的结束符 ‘\0’;

当在函数内部使用sizeof()求解由函数的形参传入的字符数组的长度时,得到的结果为指针的长度,既对应变量的字节数,而不是字符串的长度,此处一定要小心。

更多常见问题的相关技术文章,请访问常见问题栏目进行学习!

The above is the detailed content of How to calculate the length of string in C language. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template