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.

Try It Yourself
redirect icon

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.

C++
using namespace std;

// Function to count words
int countWords(string &s) {

    int count = 0;
    bool inWord = false;

    for (char c : s) {

        // Check if current character is
        // space, newline or tab
        if (c == ' ' || c == '\n' || c == '\t') {
            inWord = false;
        }

        // Start of a new word
        else if (!inWord) {
            count++;
            inWord = true;
        }
    }

    return count;
}

int main() {

    string s = "a\nyo\t";

    cout << countWords(s);

    return 0;
}
Java
class GFG {

    // Function to count words
    static int countWords(String s) {

        int count = 0;
        boolean inWord = false;

        for (int i = 0; i < s.length(); i++) {

            char c = s.charAt(i);

            // Check if current character is
            // space, newline or tab
            if (c == ' ' || c == '\n' || c == '\t') {
                inWord = false;
            }

            // Start of a new word
            else if (!inWord) {
                count++;
                inWord = true;
            }
        }

        return count;
    }

    public static void main(String[] args) {

        String s = "a\nyo\t";

        System.out.println(countWords(s));
    }
}
Python
# Function to count words
def countWords(s):

    count = 0
    inWord = False

    for c in s:

        # Check if current character is
        # space, newline or tab
        if c == ' ' or c == '\n' or c == '\t':
            inWord = False

        # Start of a new word
        elif not inWord:
            count += 1
            inWord = True

    return count


if __name__ == "__main__":

    s = "a\nyo\t"

    print(countWords(s))
C#
using System;

class GFG {

    // Function to count words
    static int countWords(string s) {

        int count = 0;
        bool inWord = false;

        foreach (char c in s) {

            // Check if current character is
            // space, newline or tab
            if (c == ' ' || c == '\n' || c == '\t') {
                inWord = false;
            }

            // Start of a new word
            else if (!inWord) {
                count++;
                inWord = true;
            }
        }

        return count;
    }

    static void Main() {

        string s = "a\nyo\t";

        Console.WriteLine(countWords(s));
    }
}
JavaScript
// Function to count words
function countWords(s) {

    let count = 0;
    let inWord = false;

    for (let c of s) {

        // Check if current character is
        // space, newline or tab
        if (c === ' ' || c === '\n' || c === '\t') {
            inWord = false;
        }

        // Start of a new word
        else if (!inWord) {
            count++;
            inWord = true;
        }
    }

    return count;
}

// Drive code
let s = "a\nyo\t";
console.log(countWords(s));

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.

C++
using namespace std;

int countWords(string &s) {

    int count = 0;
    string word;
    stringstream ss(s);

    // Extract words separated by spaces, tabs, or newlines
    while (ss >> word) {
        count++;
    }

    return count;
}

int main() {
    string s = "a\nyo\n";
    cout << countWords(s);
}
Java
class GFG {

    static int countWords(String s) {
        
        // Split by any whitespace (space, tab, newline)
        String[] words = s.trim().split("\\s+");
        return words.length;
    }

    public static void main(String[] args) {
        String s = "a\nyo\n";
        System.out.println(countWords(s));
    }
}
Python
def countWords(s):
    
    # split() handles spaces, tabs, newlines
    # and ignores empty strings
    return len(s.split())

if __name__ == '__main__':
    s = "a\nyo\n"
    print(countWords(s))  
C#
using System;

class GFG {

    static int countWords(string s) {
        
        // Split by whitespace and remove empty entries
        string[] words = s.Split(new char[]{' ', '\t', '\n'}, 
                        StringSplitOptions.RemoveEmptyEntries);
        return words.Length;
    }

    static void Main() {
        string s = "a\nyo\n";
        Console.WriteLine(countWords(s));
    }
}
JavaScript
function countWords(s) {
    
    // split by any whitespace, filter out empty strings
    return s.trim().split(/\s+/).length;
}

// Driver Code
let s = "a\nyo\n";
console.log(countWords(s)); 

Output
2
Comment