Home > Software design >  how to return the number of words in the string "sentence"
how to return the number of words in the string "sentence"

Time:11-02

I am new to coding and I want to know how to count the number of words, in the "sentence". This function uses a class, what variable should I use to return? Do I have to increment "i" to move to the next character?

int Directive::words(const char* sentence) {
    int i, word = 0;

    for (i = 0; sentence[i] != '\0'; i  ) {
        if ((sentence[i] >= 'a' && sentence[i] <= 'z') || (sentence[i] >= 'A' && sentence[i] <= 'Z')) {
            i  ;
            if (sentence[i] != ' ' && sentence[i] != '\n' && sentence[i] != '\t') {
                word  ;
                i  ;
            }
        }
        else
            return 0;
    }
    return word;
}

CodePudding user response:

The sentence must end with a '\0'

#include <iostream>

using namespace std;

int GetWordsCount(const char * Sentencee){
    int Count = 0;
    int LetterCount = 0;


    while (*Sentencee){
        if (isspace(*Sentencee) || *Sentencee == '.' || *Sentencee == ','){
            if (LetterCount)
                Count  ;

            LetterCount = 0;
            
        }
        else
            LetterCount  ;
    
        Sentencee  ;
    }

    if (LetterCount)
        Count  ;

    return Count;
}

int main() 
{ 
    const char * Sentencee = "Hello, i am learning c  !";
    cout << "Sentence: " << Sentencee << endl;
    cout << "count: " << GetWordsCount(Sentencee) << endl;

    return 0;
} 
  •  Tags:  
  • c
  • Related