VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-words-in-a-given-string/

⇱ Count words in a Given String - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count words in a Given String

Last Updated : 14 May, 2026

Given a string s consisting of lowercase English alphabets, spaces, tab characters (\t), and newline characters (\n), count the total number of words present in the string. A word is defined as a continuous sequence of lowercase English letters, while spaces, tabs, and newline characters act as separators between words.

Examples:

Input: s = "abc def"
Output: 2
Explanation: There is a space at 4th position which works as a separator between "abc" and "def".

Input: s = "a\nyo\t"
Output: 2
Explanation: There are two words in the string: "a" and "yo". The characters \n and \t act as separators, splitting the string into words.

Input: s = "a\t\tb aa"
Output: 3
Explanation: There are three words in the string: "a", "b", and "aa". The tab characters (\t\t) and space act as separators between the words.

Traversing The String - O(n) Time and O(1) Space

The idea is to traverse the string and detect the starting point of every word. We use a boolean variable inWord to track whether we are currently inside a word or not.

Whenever a lowercase letter appears after a separator like space (' '), newline ('\n'), or tab ('\t'), it means a new word has started, so we increment the count.

Consider the string: s = "a\nyo\n"

Initially, count = 0 and inWord = false, and start traversing the string character by character.

  • Character 'a' starts a new word, so increment count to 1 and mark inWord = true.
  • Character '\n' is a separator, so mark inWord = false.
  • Character 'y' starts another new word, so increment count to 2 and mark inWord = true.
  • Character 'o' continues the current word.
  • Character '\n' is again a separator, so mark inWord = false.

After traversing the complete string, the total number of words is 2.


Output
2

Using Builtin Methods - O(n) Time and O(n) Space

The idea is to use built-in string splitting methods that automatically separate words using whitespace characters like spaces, tabs ('\t'), and newlines ('\n').

After splitting the string, each extracted part represents a word. So, the total number of extracted parts gives the required answer.


Output
2
Comment
Article Tags:
Article Tags: