保存起始指針,移動指針至結束符 '\0',兩指針相减得長度。
size_t my_strlen(const char* s) {
const char* p = s;
while (*p) ++p;
return p - s;
}
用整型變量累計字符數。
size_t my_strlen(const char* s) {
size_t len = 0;
while (*s++) ++len;
return len;
}
利用數組名轉換為首地址,計算末尾地址與首地址之差。
size_t my_strlen(const char* s) {
size_t len = 0;
while (s[len]) ++len;
return len;
}
// 或
size_t my_strlen(const char* s) {
const char* end = s;
while (*end) ++end;
return end - s;
}
int main() {
char str[] = "Hello, World!";
printf("%zu\n", my_strlen(str)); // 13
return 0;
}
strlen 通常用汇編優化(如 SIMD 指令集),手寫版僅供教學。