【问题标题】:Program C count words (excluding numbers) [closed]程序 C 计数字(不包括数字)[关闭]
【发布时间】:2018-02-20 16:25:33
【问题描述】:

我遇到了很多数词的例子(比如下面链接中的例子):

Counting words in a string - c programming

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

对于数字是:

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

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

【问题讨论】:

  • 您需要tokenise 输入,然后计算有多少标记是“单词”(或者至少由完全字母字符组成,或者您的分类策略是什么)。跨度>
  • 你可以看看strtok
  • 如果单词以数字开头,如123hello,或者包含数字(he123llo),那么是否应该计算呢?
  • 那你需要考虑一下。顺便说一句,上述两个条件都不适用于他们声称要做的事情。考虑一下双空格等等。
  • 您不需要明确标记输入。一个字符一个字符的状态机也可以。

标签: c string loops if-statement counting


【解决方案1】:

假设您没有包含字母数字组合的单词,例如“foo12”,那么您可以组合您的代码 sn-ps,如下所示:

#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

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


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

【讨论】:

  • str[i] == ' ' 是一种不好的单词计数方法。例如," test" 会返回错误的结果。
  • 我同意@Groo,答案已更新,谢谢!
【解决方案2】:
#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 函数解析的字符串标记。

【讨论】:

    【解决方案3】:

    我的五分钱。:)

    #include <stdio.h>
    #include <ctype.h>
    
    size_t count_words( const char *s )
    {
        size_t n = 0;
    
        const char *p = s;
    
        while ( 1 )
        {
            int pos = 0;
    
            sscanf( p, "%*[ \t]%n", &pos );
            p += pos;
    
            if ( sscanf( p, "%*s%n", &pos ) == EOF ) break;
    
            if ( isalpha( ( unsigned char )*p ) ) ++n;
    
            p += pos;
        }
    
    
        return n;
    }
    
    int main(void) 
    {
        char s[] = "I have 12 apples";
    
        printf( "The number of words is %zu\n", count_words( s ) );
    
        return 0;
    }
    

    程序输出是

    The number of words is 3
    

    我的建议是不要将标准函数strtok 用于此类任务。首先,它可能不处理字符串文字。而且它还有一个副作用就是改变了原来的字符串。:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多