本實例編寫 length 函數模擬 strlen 功能,通過指針遍歷計算字符串長度。
length(char *s):指針 s 從首字符開始,遇到 '\0' 停止,計數器 i 即為長度。scanf("%s", str) 讀取無空格字符串,調用 length 並輸出。// Created by www.runoob.com on 15/11/9.
// Copyright © 2015年 菜鳥教程. All rights reserved.
//
#include <stdio.h>
#include <stdlib.h>
int main() {
int len;
char str[20];
printf("請輸入字符串:\n");
scanf("%s", str);
len = length(str);
printf("字符串有 %d 個字符。", len);
}
int length(char *s) {
int i = 0;
while (*s != '\0') {
i++;
s++;
}
return i;
}
請輸入字符串:
www.runoob.com
字符串有 14 個字符。
scanf("%s") 遇空格停止,無法讀取含空格字符串。strlen。