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.
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.
- 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 of words that are present in all the given sentences
- Count palindrome words in a sentence
- Reverse words in a given string
- Python program to count words in a sentence
- Count of words ending at the given suffix in Java
- Reverse middle words of a string
- Check if given words are present in a string
- Program to extract words from a given String
- Iterate over words of a String in Python
- Shortest substring of a string containing all given words
- Reverse String according to the number of words
- Print all funny words in a string
- Python | Words lengths in String
- Program to reverse words in a given string in C++
- Python | Extract words from given string
- Reverse words in a given String in Java
- Minimum Distance Between Words of a String