0

I'm trying to write a program which counts the number of words found in a string, however the program which I wrote counts the number of spaces. How do I construct this program - as efficient as possible - to count the number of words? What do I do say the string contains 4 words and 8 spaces, or if it contains no words and only spaces? What am I missing/doing wrong?

#include <stdio.h>
#include <cs50.h>
#include <ctype.h>
#include <string.h>
int main(void)
{
string text = get_string("Text: ");
int count_words = 0;
for (int i = 0, n = strlen(text); i < n; i++)
{
    if (isspace (text[i]))
    {
        count_words++;
    }
}
printf("%i\n", count_words + 1);
}

2 Answers 2

1

Detect and count the beginning of words, the space to non-space transition:

int count_words = 0;
bool begin = true;
for (int i = 0, n = strlen(text); i < n; i++) {
  if (isspace (text[i])) {
    begin = true;
  } else {
    if (begin) count_words++;
    begin = false;
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

can you please explain to me what you did?
0

Try this condition to count words:

if(text[i]!=' ' && text[i+1]==' ')
        Count=count+1;

5 Comments

If you don't mind explaining what you did? It works, but I don't see why?
bro i have placed the condition for checking "not a space" and "space after our word" so that we can slice out the word.
Conditon is : check if there is "not a space" at i. Then check if there is a space after i , if its true that means we have sliced out our word. If you still dont get it let me know.
Dont forget to Mark the answer correct only if you find it helpful.
If the input does not contain any spaces like "Hello", this approach will report 0 rather than 1.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.