search
HomeCommon ProblemHow to calculate the length of string in C language

How to calculate the length of string in C language

Jun 26, 2019 am 11:22 AM
c languagestringlength

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;
}

使用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!

Statement
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment