Signup/Sign In
LAST UPDATED: APRIL 4, 2022

C++ Program For Count A Words In Given String Even Enter No Of Space's Between String

There can be many solutions to this problem. Following is a simple and interesting solution.
The idea is to maintain two states: IN and OUT. The state OUT indicates that a separator is seen. State IN indicates that a word character is seen. We increment word count when previous state is OUT and next character is a word character.

Count A Words In Given String Even Enter No Of Space's Between String

/* C++ program to count no of words
from given input string. */
#include <bits/stdc++.h>
using namespace std;

#define OUT 0
#define IN 1

// returns number of words in str
unsigned countWords(char *str)
{
	int state = OUT;
	unsigned wc = 0; // word count

	// Scan all characters one by one
	while (*str)
	{
		// If next character is a separator, set the
		// state as OUT
		if (*str == ' ' || *str == '\n' || *str == '\t')
			state = OUT;

		// If next character is not a word separator and
		// state is OUT, then set the state as IN and
		// increment word count
		else if (state == OUT)
		{
			state = IN;
			++wc;
		}

		// Move to next character
		++str;
	}

	return wc;
}

// Driver code
int main(void)
{
	char str[] = "One two	 three\n four\tfive ";
	cout<<"No of words : "<<countWords(str);
	return 0;
}


No of words : 5

Conclusion

Here, in this tutorial, we have learned that how can we count the number of words in the string..



About the author:
Nikita Pandey is a talented author and expert in programming languages such as C, C++, and Java. Her writing is informative, engaging, and offers practical insights and tips for programmers at all levels.