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.
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.
No of words : 5
Time complexity: O(n)
This article is compiled by Narendra Kangralkar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Count words present in a string
- Check if the given string of words can be formed from words present in the dictionary
- Count words that appear exactly two times in an array of words
- Count palindrome words in a sentence
- Count of words that are present in all the given sentences
- Count of words ending at the given suffix in Java
- Python program to count words in a sentence
- Reverse words in a given string
- Count the number of words having sum of ASCII values less than and greater than k
- Python | Extract words from given string
- Python | Words lengths in String
- Minimum Distance Between Words of a String
- Iterate over words of a String in Python
- Reverse middle words of a string
- Reverse String according to the number of words