2017-09-12 20 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を入力します。

しかし、通常文章は空白で始まらないことに注意してください(これは余分な前提です)。したがって、単語の数は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関数を使用して解析された文字列トークン。

0

私の5セント。:)

#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を使用していないです。まず第一に、文字列リテラルは扱えないかもしれません。そして、元の文字列を変更する副作用があります:)