# Count words in a given string

Given a string, count number of words in it. The words are separated by following characters: space (‘ ‘) or new line (‘\n’) or tab (‘\t’) or a combination of these.

## Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution.

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.

## C++

 `/* C++ program to count no of words  ` `from given input string. */` `#include ` `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 : "``<

## C

 `/* C program to count no of words from given input string. */` `#include ` ` `  `#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 program to tes above functions ` `int` `main(``void``) ` `{ ` `    ``char` `str[] = ``"One two         three\n    four\tfive  "``; ` `    ``printf``(``"No of words : %u"``, countWords(str)); ` `    ``return` `0; ` `} `

## Java

 `/* Java program to count no of words ` `from given input string. */` `public` `class` `GFG { ` `  `  `    ``static` `final` `int` `OUT = ``0``; ` `    ``static` `final` `int` `IN = ``1``; ` `      `  `    ``// returns number of words in str ` `    ``static` `int` `countWords(String str) ` `    ``{ ` `        ``int` `state = OUT; ` `        ``int` `wc = ``0``;  ``// word count ` `        ``int` `i = ``0``; ` `         `  `        ``// Scan all characters one by one ` `        ``while` `(i < str.length()) ` `        ``{ ` `            ``// If next character is a separator, set the  ` `            ``// state as OUT ` `            ``if` `(str.charAt(i) == ``' '` `|| str.charAt(i) == ``'\n'`  `                    ``|| str.charAt(i) == ``'\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 ` `            ``++i; ` `        ``} ` `        ``return` `wc; ` `    ``} ` `      `  `    ``// Driver program to test above functions ` `    ``public` `static` `void` `main(String args[]) ` `    ``{ ` `        ``String str = ``"One two       three\n four\tfive  "``; ` `        ``System.out.println(``"No of words : "` `+ countWords(str)); ` `    ``} ` `} ` `// This code is contributed by Sumit Ghosh `

## Python3

 `# Python3 program to count words  ` `# in a given string ` `OUT ``=` `0` `IN ``=` `1` ` `  `# Returns number of words in string ` `def` `countWords(string): ` `    ``state ``=` `OUT ` `    ``wc ``=` `0` ` `  `    ``# Scan all characters one by one ` `    ``for` `i ``in` `range``(``len``(string)): ` ` `  `        ``# If next character is a separator,  ` `        ``# set the state as OUT ` `        ``if` `(string[i] ``=``=` `' '` `or` `string[i] ``=``=` `'\n'` `or` `            ``string[i] ``=``=` `'\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 ` `        ``elif` `state ``=``=` `OUT: ` `            ``state ``=` `IN ` `            ``wc ``+``=` `1` ` `  `    ``# Return the number of words ` `    ``return` `wc ` ` `  `# Driver Code ` `string ``=` `"One two         three\n four\tfive "` `print``(``"No. of words : "` `+` `str``(countWords(string))) ` ` `  `# This code is contributed by BHAVYA JAIN `

## C#

 `// C# program to count no of words ` `// from given input string.  ` `using` `System; ` ` `  `class` `GFG { ` `     `  `    ``static` `int` `OUT = 0; ` `    ``static` `int` `IN = 1; ` `     `  `    ``// returns number of words in str ` `    ``static` `int` `countWords(String str) ` `    ``{ ` `        ``int` `state = OUT; ` `        ``int` `wc = 0; ``// word count ` `        ``int` `i = 0; ` `         `  `        ``// Scan all characters one  ` `        ``// by one ` `        ``while` `(i < str.Length) ` `        ``{ ` `            ``// If next character is a separator,  ` `            ``// set the state as OUT ` `            ``if` `(str[i] == ``' '` `|| str[i] == ``'\n'``||  ` `                                  ``str[i] == ``'\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 ` `            ``++i; ` `        ``} ` `         `  `        ``return` `wc; ` `    ``} ` `     `  `    ``// Driver program to test above functions ` `    ``public` `static` `void` `Main() ` `    ``{ ` `        ``String str = ``"One two     three\n four\tfive "``; ` `        ``Console.WriteLine(``"No of words : "` `                              ``+ countWords(str)); ` `    ``} ` `} ` ` `  `// This code is contributed by Sam007. `

## PHP

 ` `

Output:

`No of words : 5`

Time complexity:
O(n)

Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.

My Personal Notes arrow_drop_up

Improved By : chitranayal, rathbhupendra

Article Tags :
Practice Tags :

5

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.