通过从头实现 strlen()(C)深入理解其内部工作原理
发布: (2026年2月6日 GMT+8 15:04)
3 min read
原文: Dev.to
Source: Dev.to
Introduction
strlen() 是一个预定义函数,用于确定给定字符串的长度。
Syntax
size_t strlen(const char *str);
Example
char str[6] = "hello";
size_t len = strlen(str); // len = 5
What Is a String in C?
在 C 语言中,字符串 不是 一个独立的数据类型。它是以空字符 ('\0') 结尾的字符数组。空字符标识字符串的结束。
Header File
strlen() 在 <string.h> 头文件中声明,该头文件包含许多标准库函数的声明。
Implementing strlen() from Scratch
Prototype
int my_strlen(const char *str);
const char *str– 指向字符串第一个字符的指针(基地址)。const防止在函数内部修改字符串,帮助避免错误。
Implementation
int my_strlen(const char *str)
{
int cnt = 0;
while (str[cnt] != '\0')
{
cnt++;
}
return cnt;
}
How It Works – Step by Step
- Argument Passing – 将字符串的基地址传递给函数。
- Counter Initialization – 将
cnt设为0,用于计数字符。 - Loop Condition – 当
str[cnt]不是空字符'\0'时,循环继续。 - Pointer Arithmetic – 虽然我们使用
str[cnt],编译器会将其视为指针算术 (*(str + cnt))。 - Incrementing the Counter – 每次迭代移动到下一个字符并递增
cnt。 - Loop Termination – 当
str[cnt]等于'\0'时,条件为假,循环结束,cnt保存了字符串的长度(不包括空终止符)。
Memory Representation
+---+---+---+---+---+---+
| h | e | l | l | o | \0|
+---+---+---+---+---+---+
^ ^
| |
base address null terminator
Why It Returns the Length of the String
- 计数所有在空终止符之前的字符。
- 空字符本身 不 被计入。
- 计数恰好在字符串结束处停止,从而得到真实的长度。
Final Understanding
通过从头实现 strlen(),你可以看到:
- 字符串在内存中是以
'\0'结尾的字符序列。 - 空字符在标记字符串结束方面的重要性。
- 指针算术和简单循环是如何在 C 中用于遍历字符串的。