Studytonight is now part of the GUVI universe. Explore GUVI →
🤩 New Cool Developer Tools for you. Explore →
FREE JavaScript Video Series Start Learning →
Signup/Sign In
Tests
MCQs to test your knowledge.
Compilers
Compilers to execute code in browser.
Index
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.

Learn to Code
Learn and practice coding side-by-side.
NEW
C language Course
115+ coding exercises
Javascript Course
85+ coding exercises

AltStyle によって変換されたページ (->オリジナル) /