简体   繁体   English

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

[英]Counting words in a string - c programming

I need to write a function that will count words in a string.我需要编写一个函数来计算字符串中的单词。 For the purpose of this assignment, a "word" is defined to be a sequence of non-null, non-whitespace characters, separated from other words by whitespace.出于此分配的目的,“单词”被定义为一系列非空、非空白字符,通过空白与其他单词分隔。

This is what I have so far:这是我到目前为止所拥有的:

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;

I am not sure if it works or not because I can't test it until my whole program is finished and I am not sure it will work, is there a better way of writing this function?我不确定它是否有效,因为在我的整个程序完成之前我无法测试它并且我不确定它是否有效,有没有更好的方法来编写这个函数?

You needed你需要

int words(const char sentence[])
{
}

(note braces). (注意大括号)。

For loops go with ; For 循环与; instead of , .而不是, .


Without any disclaimer, here's what I'd have written:没有任何免责声明,这是我写的:

See it live http://ideone.com/uNgPL现场观看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"));
}

See the following example, you can follow the approach : count the whitespace between words .看下面的例子,你可以按照方法:计算单词之间的空格。

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

To test :去测试 :

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

Output :输出 :

Words = 4
#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;
}
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;
}

Here is one of the solutions.这是解决方案之一。 It counts words with multiple spaces or just space or space followed by the word.它计算带有多个空格的单词,或者只是空格或空格后跟单词。

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

Here is another solution:这是另一个解决方案:

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

I found the posted question after finishing my function for a C class I'm taking.在完成我正在学习的 C 课程的功能后,我发现了发布的问题。 I saw some good ideas from code people have posted above.我从上面发布的代码中看到了一些好主意。 Here's what I had come up with for an answer.这是我想出的答案。 It certainly is not as concise as other's, but it does work.它当然不像其他的那样简洁,但它确实有效。 Maybe this will help someone in the future.也许这将有助于将来的某人。

My function receives an array of chars in. I then set a pointer to the array to speed up the function if it was scaled up.我的函数接收到一个字符数组。然后我设置一个指向该数组的指针以加速函数(如果它被放大)。 Next I found the length of the string to loop over.接下来我找到了要循环的字符串的长度。 I then use the length of the string as the max for the 'for' loop.然后我使用字符串的长度作为“for”循环的最大值。 I then check the pointer which is looking at array[0] to see if it is a valid character or punctuation.然后我检查正在查看数组 [0] 的指针以查看它是否是有效字符或标点符号。 If pointer is valid then increment to next array index.如果指针有效,则递增到下一个数组索引。 The word counter is incremented when the first two tests fail.当前两个测试失败时,字计数器增加。 The function then will increment over any number of spaces until the next valid char is found.然后该函数将递增任意数量的空格,直到找到下一个有效字符。 The function ends when null '\0' or a new line '\n' character is found.该函数在找到 null '\0' 或换行符 '\n' 时结束。 Function will increment count one last time right before it exit to account for the word preceding null or newline.函数将在退出前最后一次将 count 递增一次,以说明 null 或换行符之前的单词。 Function returns count to the calling function.函数将计数返回给调用函数。

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

I had this as an assignment...so i know this works.我有这个作为一个任务......所以我知道这是有效的。 The function gives you the number of words, average word length, number of lines and number of characters.该函数为您提供字数、平均字长、行数和字符数。 To count words, you have to use isspace() to check for whitespaces.要计算单词,您必须使用 isspace() 来检查空格。 if isspace is 0 you know you're not reading whitespace.如果 isspace 为 0,您就知道您没有读取空格。 wordCounter is a just a way to keep track of consecutive letters. wordCounter 只是一种跟踪连续字母的方法。 Once you get to a whitespace, you reset that counter and increment wordCount.一旦你到达一个空白,你重置那个计数器并增加 wordCount。 My code below:我的代码如下:

Use isspace(c) to使用 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);
}

I know this is an old thread, but perhaps someone needs a simple solution, just checks for blank space in ascii and compares current char to that while also makign sure first char is not a space, cheers!我知道这是一个旧线程,但也许有人需要一个简单的解决方案,只需检查 ascii 中的空格并将当前字符与该字符进行比较,同时确保第一个字符不是空格,干杯!

int count_words(string text){
int counter = 1;
int len = strlen(text);
for(int i = 0; i < len; i++){
    if(text[i] == 32 && i != 0) {
        counter++;
    }
}
return counter;}

Here is one solution.这是一种解决方案。 This one will count words correctly even if there are multiple spaces between words, no spaces around interpuncion symbols, etc. For example: I am,My mother is.即使单词之间有多个空格,交叉符号周围没有空格等,这个也会正确计算单词。例如:我是,我妈妈是。 Elephants ,fly away.大象,飞走了。

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

this is a simpler function to calculate the number of words这是一个更简单的计算字数的函数

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM