程式碼
#include <stdio.h>
#include <string.h>
int main() {
printf("%zu\n", strlen("Welcome\n")); // 輸出 8
return 0;
}
解析
- 字串字面量
"Welcome\n" 在記憶體中為:W e l c o m e \n \0 (共 9 bytes)。
strlen 回傳 字串長度 (不含結束符 \0):W e l c o m e \n = 8 字元。
sizeof("Welcome\n") 回傳 9 (含 \0)。
手寫 strlen 實作
size_t my_strlen(const char *s) {
size_t len = 0;
while (*s++) len++;
return len;
}
// 或遞迴版
size_t my_strlen_rec(const char *s) {
return *s ? 1 + my_strlen_rec(s+1) : 0;
}
注意事項
- 傳入指針必須指向有效的以 \0 結尾的字串,否則 UB。
- 回傳型別
size_t (無符號),格式字串用 %zu (C99)。