计算字符串中的单词 - c编程

时间:2012-10-02 21:44:43

标签: c string function

我需要编写一个函数来计算字符串中的单词。为了 该赋值的目的是将“单词”定义为序列 非空,非空白字符,与其他单词分开 空格。

这是我到目前为止所做的:

int words(const char sentence[ ]);

int i, length=0, count=0, last=0;
length= strlen(sentence);

for (i=0, i<length, i++)
 if (sentence[i] != ' ')
     if (last=0)
        count++;
     else
        last=1;
 else
     last=0;

return count;

我不确定它是否有效,因为在我的整个程序完成之前我无法测试它并且我不确定它是否会起作用,是否有更好的方法来编写此函数?

13 个答案:

答案 0 :(得分:6)

你需要

int words(const char sentence[])
{
}

(注意大括号)。

For循环使用;代替,


没有任何免责声明,这就是我所写的内容:

直播 http://ideone.com/uNgPL

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

int words(const char sentence[ ])
{
    int counted = 0; // result

    // state:
    const char* it = sentence;
    int inword = 0;

    do switch(*it) {
        case '\0': 
        case ' ': case '\t': case '\n': case '\r': // TODO others?
            if (inword) { inword = 0; counted++; }
            break;
        default: inword = 1;
    } while(*it++);

    return counted;
}

int main(int argc, const char *argv[])
{
    printf("%d\n", words(""));
    printf("%d\n", words("\t"));
    printf("%d\n", words("   a      castle     "));
    printf("%d\n", words("my world is a castle"));
}

答案 1 :(得分:4)

请参阅以下示例,您可以按照以下方法:计算单词之间的空白。

int words(const char *sentence)
{
    int count=0,i,len;
    char lastC;
    len=strlen(sentence);
    if(len > 0)
    {
        lastC = sentence[0];
    }
    for(i=0; i<=len; i++)
    {
        if((sentence[i]==' ' || sentence[i]=='\0') && lastC != ' ')
        {
            count++;
        }
        lastC = sentence[i];
    }
    return count;
}

测试:

int main() 
{ 
    char str[30] = "a posse ad esse";
    printf("Words = %i\n", words(str));
}

输出:

Words = 4

答案 2 :(得分:2)

#include <ctype.h> // isspace()

int
nwords(const char *s) {
  if (!s) return -1;

  int n = 0;
  int inword = 0;
  for ( ; *s; ++s) {
    if (!isspace(*s)) {
      if (inword == 0) { // begin word
        inword = 1;
        ++n;
      }
    }
    else if (inword) { // end word
      inword = 0;
    }
  }
  return n;
}

答案 3 :(得分:1)

bool isWhiteSpace( char c )
{
    if( c == ' ' || c == '\t' || c == '\n' )
        return true;
    return false;
}

int wordCount( char *string )
{
    char *s = string;
    bool inWord = false;
    int i = 0;

    while( *s )
    {
        if( isWhiteSpace(*s))
        {
            inWord = false;
            while( isWhiteSpace(*s) )
                s++;
        }
        else
        {
            if( !inWord )
            {
                inWord = true;
                i++;
            }
            s++;
        }
    }

    return i;
}

答案 4 :(得分:1)

这是其中一种解决方案。它计算具有多个空格或仅空格或空格后跟单词的单词。

#include <stdio.h>
int main()
{
    char str[80];
    int i, w = 0;
    printf("Enter a string: ");
    scanf("%[^\n]",str);

    for (i = 0; str[i] != '\0'; i++)
    {
       
        if((str[i]!=' ' && str[i+1]==' ')||(str[i+1]=='\0' && str[i]!=' '))
        {
            w++;
        }
        
    }

    printf("The number of words = %d", w );

    return 0;
}

答案 5 :(得分:0)

这是另一种解决方案:

#include <string.h>

int words(const char *s)
{
    const char *sep = " \t\n\r\v\f";
    int word = 0;
    size_t len;

    s += strspn(s, sep);

    while ((len = strcspn(s, sep)) > 0) {
        ++word;
        s += len;
        s += strspn(s, sep);
    }
    return word;
}

答案 6 :(得分:0)

#include<stdio.h>

int main()   
{    
char str[50];    
int i, count=1;  
printf("Enter a string:\n");    
gets(str);    
for (i=0; str[i]!='\0'; i++)   
        {
        if(str[i]==' ')    
                {
                count++;
                }
        }
printf("%i\n",count);    
}

答案 7 :(得分:0)

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

int getN(char *);


int main(){
    char str[999];
    printf("Enter Sentence: "); gets(str);
    printf("there are %d words", getN(str));
}


int getN(char *str){
    int i = 0, len, count= 0;
    len = strlen(str);
    if(str[i] >= 'A' && str[i] <= 'z')
       count ++;


    for (i = 1; i<len; i++)
        if((str[i]==' ' || str[i]=='\t' || str[i]=='\n')&& str[i+1] >= 'A' && str[i+1] <= 'z')
        count++;


return count;
}

答案 8 :(得分:0)

#include <stdio.h>

int wordcount (char *string){

    int n = 0; 

    char *p = string ;
    int flag = 0 ;

    while(isspace(*p)) p++;


    while(*p){
        if(!isspace(*p)){
            if(flag == 0){
                flag = 1 ;
                n++;
            }
        }
        else flag = 0;
        p++;
    }

    return n ;
}


int main(int argc, char **argv){

    printf("%d\n" , wordcount("    hello  world\nNo matter how many newline and spaces"));
    return 1 ;
}

答案 9 :(得分:0)

在完成我正在服用的C级课程后,我找到了发布的问题。我从上面发布的代码中看到了一些好的想法。这就是我想出的答案。它当然不像其他的那样简洁,但确实有效。也许这将有助于将来的人。

我的函数接收一个字符数组。然后我设置一个指向数组的指针,以便在按比例放大时加速该函数。接下来,我发现要循环的字符串的长度。然后我使用字符串的长度作为'for'循环的最大值。   然后我检查正在查看数组[0]的指针,看它是否是有效的字符或标点符号。如果指针有效,则递增到下一个数组索引。当前两个测试失败时,字计数器会递增。然后,该函数将在任意数量的空格上递增,直到找到下一个有效字符。   当找到'\ 0'或新的'\ n'字符时,该函数结束。函数将在退出之前最后一次递增计数,以便考虑前面的null或换行符之前的单词。函数返回count到调用函数。

#include <ctype.h>

char wordCount(char array[]) {
    char *pointer;    //Declare pointer type char
    pointer = &array[0];  //Pointer to array

    int count; //Holder for word count
    count = 0; //Initialize to 0.

    long len;  //Holder for length of passed sentence
    len = strlen(array);  //Set len to length of string

    for (int i = 0; i < len; i++){

        //Is char punctuation?
        if (ispunct(*(pointer)) == 1) {
            pointer += 1;
            continue;
        }
        //Is the char a valid character?
        if (isalpha(*(pointer)) == 1) {
            pointer += 1;
            continue;
        }
        //Not a valid char.  Increment counter.
        count++;

        //Look out for those empty spaces. Don't count previous
        //word until hitting the end of the spaces.
        if (*(pointer) == ' ') {
            do {
                pointer += 1;
            } while (*(pointer) == ' ');
        }

        //Important, check for end of the string
        //or newline characters.
        if (*pointer == '\0' || *pointer == '\n') {
            count++;
            return(count);
        }
    }
    //Redundent return statement.
    count++;
    return(count);
}

答案 10 :(得分:0)

我将其作为任务...所以我知道这可行。 该功能为您提供单词数,平均单词长度,行数和字符数。 要计算单词数,您必须使用isspace()来检查空格。如果isspace为0,则表示您没有读取空格。 wordCounter是跟踪连续字母的一种方法。进入空白后,您将重置该计数器并递增wordCount。我的代码如下:

使用isspace(c)

#include <stdio.h>
#include <ctype.h>

int main() {
  int lineCount = 0;
  double wordCount = 0;
  double avgWordLength = 0;
  int numLines = 0;
  int wordCounter = 0;
  double nonSpaceChars = 0;
  int numChars = 0;
  printf("Please enter text.  Use an empty line to stop.\n"); 
  while (1) {
      int ic = getchar();
      if (ic < 0)    //EOF encountered
          break;
      char c = (char) ic;
      if (isspace(c) == 0 ){
      wordCounter++;
      nonSpaceChars++;
    }
      if (isspace(c) && wordCounter > 0){
      wordCount++;
      wordCounter =0;
    }
      if (c == '\n' && lineCount == 0) //Empty line
      { 
          break; 
      }
      numChars ++;
      if (c == '\n') {
          numLines ++;
          lineCount = 0;
      }
      else{
          lineCount ++;
    }
  }
  avgWordLength = nonSpaceChars/wordCount;
  printf("%f\n", nonSpaceChars);
  printf("Your text has %d characters and %d lines.\nYour text has %f words, with an average length of %3.2f ", numChars, numLines, wordCount, avgWordLength);
}

答案 11 :(得分:-1)

这是一个解决方案。即使单词之间有多个空格,没有空格符号等空间,这个也会正确计算单词。例如:我是,我的母亲是。大象,飞走了。

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


int countWords(char*);


int main() {
    char string[1000];
    int wordsNum;

    printf("Unesi nisku: ");
    gets(string);  /*dont use this function lightly*/

    wordsNum = countWords(string);

    printf("Broj reci: %d\n", wordsNum);

    return EXIT_SUCCESS;
}


int countWords(char string[]) {
    int inWord = 0,
        n,
        i,
        nOfWords = 0;

    n = strlen(string);

    for (i = 0; i <= n; i++) {
        if (isalnum(string[i]))
            inWord = 1;
        else
            if (inWord) {
                inWord = 0;
                nOfWords++;
            }
    }

    return nOfWords;
}

答案 12 :(得分:-1)

这是一个计算单词数量的简单函数

const call_opts = {
                    to: options.to_land,
                    from: twilio_config.from,
                    url: voice_url // which says what to give response if customer picks the call
                  };

const twilio = Twilio(twilio_config.sid, twilio_config.token);      

twilio.makeCall(call_opts, cb)

int counter_words(char* a){` // go through chars in a // if ' ' new word int words=1; int i; for(i=0;i<strlen(a);++i) { if(a[i]==' ' && a[i+1] !=0) { ++words; } }