經典之一,比較簡單,C語言中字符串用char數組表示,以'\0'作爲結尾,請看大屏幕:
//計算一個字符串的長度
#include <stdio.h>
#include <stdlib.h>
int main()
{
char str[20];
char *p;
int cnt =0;
//輸入一個字符串
printf("input a word.\n");
scanf("%s",&str);
//計算其長度 字符串以\0結尾
for (p = str; *p != '\0'; ++p)
++cnt;
//輸出結果
printf("It has %d chars.\n",cnt);
return 0;
}