2017-09-12 33 views
0

我也接触过很多字数统计的例子(像在下面的链接)的:方案C计字(不包括数字)

Counting words in a string - c programming

if(str[i]==' ') 
{ 
    i++; 
} 

和数字是:

if(str[i]>='0' && str[i]<='9') 
{ 
    i++; 
} 

但是如果输入是'我有12个苹果'。我只希望输出显示“字数= 3”?

+3

你需要[tokenise](https://stackoverflow.com/questions/266357/tokenizing-strings-in-c)输入,然后计算有多少令牌是“单词”(或者至少包含完全由字母组成的字符,或者其他任何分类策略)。 – hnefatl

+2

你可以看看'strtok' –

+4

如果这个单词以数字开头,比如123hello,或者包含一个数字('he123llo'),那么该怎么算呢? – Groo

回答

2

假设你没有包含字母数字组合,如“foo12”的话,那么你可以结合你的代码片段,像这样:

#include <stdio.h> 
#include <string.h> 

int main(void) 
{ 
    char str[] = "Bex 67 rep"; 
    int len = strlen(str); 
    int count = 0, i = 0; 
    while(str[i] != '\0') 
    { 
     if(str[i] == ' ') 
     { 
      if(i + 1 < len && ! (str[i + 1] >= '0' && str[i + 1] <= '9') && str[i + 1] != ' ') 
       count++; 
     } 
     i++; 
    } 
    printf("Word count = %d\n", count + 1); // Word count = 2 
    return 0; 
} 

,你遍历字符串的每一个字符,当你找到一个空格时,你检查 - 如果你不在字符串的最后一个字符 - 如果下一个字符是而不是一个数字或空格。如果是这样的话,那么你可以假设你遇到的空白是一个单词的前面,因此提升count

但是请注意,通常senteces不以空格开始(这是对此答案的额外假设),因此单词的数量比count多一个。


在现实生活中,使用strtok()和检查每个令牌的有效性,因为这方法只是为了示范和应被视为一个不错的办法

+0

'str [i] =='''是计算单词的不好方法。例如''test''会返回错误的结果。 – Groo

+0

我同意@Groo,回答更新,谢谢! – gsamaras

0
#include <stdio.h> 
#include <string.h> 

int main() 
{ 
    char str[] ="I have 12 apples"; 
    char * pch; 
    unsigned long ul; 
    int cnt=0; 

    pch = strtok (str," ,.-"); 
    while (pch != NULL) 
    { 
     ul = strtoul (pch, NULL, 0); 
     pch = strtok (NULL, " ,.-"); 
     printf("%d\n", ul); 
     if(ul == 0) 
      cnt++; 
    } 
    printf("count is %d\n", cnt); 
    return 0; 
} 

使用strtok函数解析的字符串标记。