7

我需要编写一个函数来计算字符串中的单词。出于此分配的目的,“单词”被定义为一系列非空、非空白字符,通过空白与其他单词分隔。

这是我到目前为止所拥有的:

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;

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

4

13 回答 13

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"));
}
于 2012-10-02T22:11:26.383 回答
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
于 2012-10-02T22:03:07.527 回答
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;
}
于 2012-10-02T22:21:21.010 回答
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;
}
于 2015-03-19T14:23:23.830 回答
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;
}
于 2021-01-31T16:47:34.103 回答
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;
}
于 2012-10-23T21:26:43.380 回答
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);    
}
于 2014-03-18T10:16:06.477 回答
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;
}
于 2015-04-18T00:55:34.240 回答
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 ;
}
于 2015-08-04T15:46:10.350 回答
0

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

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

#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);
}
于 2017-11-07T20:09:26.020 回答
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);
}
于 2019-01-24T21:58:48.973 回答
-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;
}
于 2013-09-02T20:57:06.053 回答
-1

这是一个更简单的计算字数的函数

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;
      }
 }

return words;}

于 2016-07-08T09:14:08.113 回答