Reputation: 11
I wrote a code that counts how many words are there in a sentence, but it does not work in cases like this for example:
"hello world."
It needs to return that there are 2 words, but it returns 4 because of the spaces. It's only good for the case of one space between each word. This is my code:
int counthowmanywordsinasentence(char sentence[])// help forfunc7
{
int count = 0, i;
for (i = 0;sentence[i] != '\0';i++)
{
if (sentence[i] == ' ')
count++;
}
return (count+1);
}
Upvotes: 0
Views: 143
Reputation: 1840
You'll have to decide what is a word first :) let's assume a word is any sequence of characters with at least one alphabetic character (A-Za-z). then you can follow @Abhilash's suggestion to complete your code.
int wordcount(char *sentence) {
int count = 0;
int is_word = 0;
int i;
for(i=0; sentence[i]!='\0'; i++) {
if(isalpha(sentence[i])) {
is_word = 1;
}
if(sentence[i] == ' ' && is_word) {
count++;
is_word = 0;
}
}
return count + is_word;
}
Upvotes: 0
Reputation: 38909
So sscanf
already does what you need it will eat any number of whitespaces before a string including tabs. This algorithm is safe with leading or trailing spaces.
int countHowManyWordsInASentence(char* sentence){
int result = 0;
int i = 0;
while(sscanf(sentence, "%*s%n", &i) != EOF){
sentence += i;
result++;
}
return result;
}
sscanf
is extremely versatile you can easily read out each word as follows:
int countHowManyWordsInASentence(char* sentence){
int result = 0;
int size = strlen(sentence);
if(size > 0){
char* word = (char*)malloc((size + 1) * sizeof(char));
for(int i = 0; sscanf(sentence, "%s%n", word, &i) > 0; sentence += i){
result++;
}
free(word);
}
return result;
}
Upvotes: 1
Reputation: 40145
int counthowmanywordsinasentence(char sentence[])
{
int count = 0, i;
char ch, pre = ' ';
for (i = 0; (ch=sentence[i]) != '\0'; i++, pre = ch)
{
if (pre == ' ' && ch != ' ')//reckon the rise
count++;
}
return count;
}
Upvotes: 0
Reputation: 23016
You can safely replace your if
by this new version:
if (sentence[i] == ' ' && sentence[i+1] != ' ')
Which means you will be only counting the last space in each space sequence. So in your case of 4 contiguous spaces, you will count only the last one.
You will still need to decide what to do in these two cases:
" hello world."
"hello world "
As you need to know if these should count as 2 or 3 words in both cases.
Upvotes: 1
Reputation: 52071
This is the simplest of all answers, just add 2 lines
#include <stdio.h>
int counthowmanywordsinasentence(char sentence[])// help forfunc7
{
int count = 0, i;
for (i = 0;sentence[i] != '\0';i++)
{
if (sentence[i] == ' ')
count++;
while (sentence[i] == ' ')
i++;
}
return (count+1);
}
Upvotes: 1
Reputation: 3511
Use a flag. If you encounter a space & flag is not set, set the flag and increment count. If space is encountered & flag is set , just ignore that case. And if flag is set & char(i.e. sentence[i]) is not space, reset flag.
Upvotes: 2