strlen是C语言标准库中的字符串处理函数,定义在string.h头文件中,核心作用是计算以空字符 结尾的字符串的实际长度,不包含末尾的空字符本身。下面先通过一张示意图直观了解字符串存储和strlen计算的关系。
strlen函数的基本语法
strlen的函数原型如下:
#include <string.h> size_t strlen(const char *str);
参数str是指向待计算长度的字符串的指针,函数的返回值是size_t类型,也就是无符号整数,代表字符串的长度。需要注意的是,传入的str必须指向一个以 结尾的字符串,否则strlen会继续向后遍历内存,直到遇到 为止,这种情况下得到的结果是未定义的。
strlen的基础使用示例
下面是几个常见的使用场景示例:
计算普通字符串字面量的长度
#include <stdio.h>
#include <string.h>
int main() {
const char *str = "hello world";
// 计算字符串长度
size_t len = strlen(str);
printf("字符串长度: %zun", len); // 输出 11,不包含末尾隐含的
return 0;
}
计算字符数组初始化的字符串长度
#include <stdio.h>
#include <string.h>
int main() {
// 字符数组初始化,会自动在末尾添加
char arr[] = "test";
size_t len = strlen(arr);
printf("字符数组字符串长度: %zun", len); // 输出 4
return 0;
}
使用strlen的常见注意事项
- 不要对没有 结尾的字符数组使用strlen,比如手动初始化字符数组但没有添加结束符的情况:
#include <stdio.h>
#include <string.h>
int main() {
// 该数组没有 结尾,不是合法字符串
char arr[3] = {'a', 'b', 'c'};
// 错误用法,结果未定义
size_t len = strlen(arr);
printf("长度: %zun", len);
return 0;
}
- strlen的返回值是size_t类型,是无符号整数,不要和有符号整数直接做减法比较,否则可能出现逻辑错误,比如判断两个字符串长度差的时候:
#include <stdio.h>
#include <string.h>
int main() {
const char *s1 = "abc";
const char *s2 = "ab";
// 错误写法,strlen返回无符号数,减法结果不会是负数
if (strlen(s1) - strlen(s2) < 0) {
printf("s1比s2短n");
} else {
printf("s1比s2长或相等n"); // 实际会走到这里
}
return 0;
}
如果要比较长度差,建议先转换成有符号整数再计算,或者分别判断两个长度的大小。
strlen和sizeof的区别
很多初学者容易混淆strlen和sizeof,两者的核心区别如下:
| 对比项 | strlen | sizeof |
|---|---|---|
| 作用 | 计算字符串的实际字符数,不包含 | 计算变量或类型占用的内存字节数 |
| 处理对象 | 仅能处理以 结尾的字符串 | 可以处理任意变量、类型、数组等 |
| 运行时/编译时 | 运行时计算 | 编译时计算 |
比如下面的例子可以直观看到两者的差异:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "hello";
printf("strlen结果: %zun", strlen(str)); // 输出5
printf("sizeof结果: %zun", sizeof(str)); // 输出6,包含 的1个字节
return 0;
}