vendredi 7 mai 2021

how to find number of words in a sentence in a string?

how to find number of words in a sentence. when the sentence have uneven spacing. for example. "how are you?"

in between "how" and "are", there re 5 spaces and in between "are" and "you" only one space. my code below, but not getting expected output.

string s = "how     are you?";

int vowels = 0;
int consonants = 0;
int words =1 ;

for(int i= 0; i < s.length(); i++){

    if (s[i]=='A'|| s[i]=='E'||s[i]=='I'||s[i]=='O'||s[i]=='U'||s[i]=='a'||s[i]=='e'||s[i]=='i'||s[i]=='o'||s[i]=='u'){
        vowels+=1;
    }
    else if ((s[i] == '     ') {
        words +=1;
    }
    else if ((s[i] == ' ')){
        words +=1;
    }


    else {
        consonants+=1;
    }


}

cout<<"number of vowels "<<vowels<<endl;
cout<<"number of words "<<words<<endl;
cout<<"number of consonants "<<consonants<<endl;


return 0;

}

Aucun commentaire:

Enregistrer un commentaire