获取字符或字符串的长度:strlen()
发布时间:2023-06-13 00:39:51
节内存,字符串通常使用null结尾的数组表示,需要确定字符串长度才能正确操作。C语言提供了一个内置的函数,即strlen(),可以获取字符串长度。
使用方法:
1.包含头文件string.h。
2.传递一个字符串作为参数,返回字符串长度(不包括null结尾)。
下面是示例代码:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, world!";
int length = strlen(str);
printf("The length of the string \"%s\" is %d.
", str, length);
return 0;
}
输出结果:
The length of the string "Hello, world!" is 13.
Tips:
1.如果字符串中包含null字符,strlen()会返回null字符前的长度。
2.如果字符串未以null结尾,则无法正确计算其长度,可能导致程序出错或产生不可预知的结果。因此我们应该始终确保字符串以null结尾或使用字符串操作函数(如strncpy()、strncat()),以保证字符串的完整性。
