題目來源:
https://acm.zzuli.edu.cn/zzuliacm/problem.php?id=1161
Description
編寫一函數len,求一個字符串的長度,注意該長度不計空格。要求用字符指針實現。在主函數中輸入字符串,調用該len函數后輸出其長度。
int len(char *sp)
{
//實現sp所指串的長度,不計空格。
}
Input
輸入一個字符串,以回車結束,長度不超過100。
Output
輸出一個整數,單獨占一行。
Sample Input
What day is today?
Sample Output
15
題意描述:
輸入一個字符串(長度不超過100)
調用len函數計算該字符串的長度,不計空格
解題思路:
在len函數中判斷是否空格,不是計數變量加一,最后返回即可
程序代碼:
1 #include<stdio.h>
2 #include<string.h>
3 int len(char *str); 4 int main() 5 { 6 char str[110]; 7 gets(str); 8 printf("%d\n",len(str)); 9 } 10 int len(char *str) 11 { 12 int i,l,count=0;//注意計數變量的初始化
13 l=strlen(str); 14 for(i=0;i<l;i++) 15 if(str[i] != ' ') 16 count++; 17 return count; 18 }
錯誤分析:
注意計數變量的初始化