C programming

2007-09-09 9:22 am
如何在C中計字數
謝謝~

回答 (1)

2007-09-09 10:43 am
✔ 最佳答案
#include < stdio.h >

int count_words(char* str)
{
int i;
bool mode = false;// true - word mode, false - space mode
int cnt = 0;
for (i=0; str[i] != '\0'; i++)
{
switch (str[i])
{
case ' ': case '\n': case '\t':// separator
if (mode)
cnt++;
mode = false;
break;
default:
mode = true;
break;
};
}
if (mode)
cnt++;
return cnt;
}

int main()
{
char* str = "this is line one\nthis is line two";
char str2[] = " this \n\t is another \t \t test \t\t";

printf("# of words in\n[%s] = %d\n", str, count_words(str));
printf("# of words in\n[%s] = %d\n", str2, count_words(str2));

return 0;
}


收錄日期: 2021-04-13 13:23:37
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20070909000051KK00369

檢視 Wayback Machine 備份