利用字元陣列計算單詞個數
阿新 • • 發佈:2018-12-20
輸入一行字元,統計其中有多少個單詞,要求每個單詞之間用空格分開,且最後字元不能為空格。 這個題設限制太多,先完成,在做一些拓展。
第一次程式碼:
#include<stdio.h>
#include<stdlib.h>
/* 字元陣列的應用 */
/* written by Chen Gengru */
/* updated on 2018-11-8 */
int main()
{
char cString[100]; /* 定義儲存字串的陣列 */
int iIndex, iWord = 1;
char cBlank; /* 陣列字串 */
gets (cString); /* 輸入字串 */
if (cString[0] == '\n') /* 判斷字串為空的情況 */
{
printf("There is no char\n");
}
else if (cString[0] == ' ') /* 判斷第一個字元為空格的情況 */
{
printf("The first char is just a blank\n");
}
else
{
for (iIndex = 0; cString[iIndex] != '\0'; iIndex++)
{
cBlank = cString[ iIndex];
if (cBlank == ' ') /* 每輸入一個空格單詞數加1 */
{
iWord++;
}
}
if (iWord == 1)
{
printf("There is 1 word.\n");
}
else
{
printf("There are %d words\n", iWord);
}
}
return 0;
}
測試結果:
1,輸入’I LOVE CHINA’: 2,首位輸入空格: 3,首位輸入回車: ?!怎麼回事?原來在輸入回車的時候,cString[0]應該為\0而不是\n。
更改:
#include<stdio.h>
#include<stdlib.h>
/* 字元陣列的應用 */
/* written by Chen Gengru */
/* updated on 2018-11-8 */
int main()
{
char cString[100]; /* 定義儲存字串的陣列 */
int iIndex, iWord = 1;
char cBlank; /* 陣列字串 */
gets(cString); /* 輸入字串 */
if (cString[0] == '\0') /* 判斷字串為空的情況 */
{
printf("There is no char\n");
}
else if (cString[0] == ' ') /* 判斷第一個字元為空格的情況 */
{
printf("The first char is just a blank\n");
}
else
{
for (iIndex = 0; cString[iIndex] != '\0'; iIndex++)
{
cBlank = cString[iIndex];
if (cBlank == ' ') /* 每輸入一個空格單詞數加1 */
{
iWord++;
}
}
if (iWord == 1)
{
printf("There is 1 word.\n");
}
else
{
printf("There are %d words\n", iWord);
}
}
return 0;
}
成功。
思考:能不能不管開頭輸入空格還是回車,結尾能不能輸空格,或者如果手抖在打單詞的時候連續輸入了兩個空格,都可以直接輸出正確單詞個數? 關鍵在於:連續輸入空格和首末輸入的判斷。其實也蠻好解決的。
程式碼:
#include<stdio.h>
#include<stdlib.h>
/* 字元陣列的應用 */
/* written by Chen Gengru */
/* updated on 2018-11-8 */
int main()
{
char cString[100]; /* 定義儲存字串的陣列 */
int iIndex, iWord = 0;
char cBlank; /* 陣列字串 */
gets(cString); /* 輸入字串 */
for (iIndex = 0; cString[iIndex] != '\0'; iIndex++)
{
cBlank = cString[iIndex];
if (cBlank == ' ') /* 每輸入一個空格單詞數加1 */
{
iWord++;
}
if (cString[iIndex] == ' ' && cString[iIndex-1] == ' ')
{
iWord--; /* 若連續輸入空格,只記作一次 */
}
if (cString[iIndex] == ' ' && cString[iIndex+1] == '\0')
{
iWord--; /*
}
}
if (cString[0] == ' ') /* 判斷開頭是否是空格 */
{
iWord--;
}
iWord++; /* iWord初始值為0,故最後要加1 */
printf("number of words:%d\n", iWord);
return 0;
}
成功!