Sunday, November 17, 2024
Google search engine
HomeLanguagesCount words in a given string

Count words in a given string

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

Recommended Practice

Method 1: 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 <stdio.h>
 
#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 test above functions
int main(void)
{
    char str[] = "One two         three\n    four\tfive  ";
    printf("No of words : %u", countWords(str));
    return 0;
}


C++




/* C++ program to count no of words
from given input string. */
#include <bits/stdc++.h>
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 : "<<countWords(str);
    return 0;
}
 
// This is code is contributed by rathbhupendra


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




<?php
// PHP program to count no of
// words from given input string
$OUT = 0;
$IN = 1;
 
// returns number of words in str
function countWords($str)
{
    global $OUT, $IN;
    $state = $OUT;
    $wc = 0; // word count
    $i = 0;
     
    // Scan all characters one by one
    while ($i < strlen($str))
    {
        // 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 Code
$str = "One two         three\n four\tfive ";
echo "No of words : " . countWords($str);
 
// This code is contributed
// by ChitraNayal
?>


Javascript




<script>
// javascript program to count no of words
// from given input string.
    var OUT = 0;
    var IN = 1;
     
    // returns number of words in str
    function countWords( str)
    {
        var state = OUT;
        var wc = 0; // word count
        var 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
        var str = "One two     three\n four\tfive ";
        document.write("No of words : "
                              + countWords(str));
 
// This code is contributed by bunnyram19.
</script>


Output

No of words : 5

Time complexity: O(n)
Auxiliary Space: O(1)

This article is compiled by Aarti_Rathi and Narendra Kangralkar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Method 2: using String.split() method

  1. Get the string to count the total number of words.
  2. Check if the string is empty or null then return 0.
  3. Use split() method of String class to split the string on whitespaces.
  4. The split() method breaks the given string around matches of the given regular expression and returns an array of string.
  5. The length of the array is the number of words in the given string.
  6. Now, print the result.

Below is the implementation of the above approach:

C




// C program to count total
// number of words in the string
#include <stdio.h>
#include <string.h>
 
// Function to count total number
// of words in the string
int countWords(char str[])
{
    // Check if the string is null
    // or empty then return zero
    if (strlen(str) == 0) {
        return 0;
    }
    // Splitting the string around
    // matches of the given regular
    // expression
    char* token;
    char* delim = " \n\t";
    token = strtok(str, delim);
    int count = 0;
    while (token != NULL) {
        count++;
        token = strtok(NULL, delim);
    }
 
    // Return number of words
    // in the given string
    return count;
}
 
int main()
{
    // Given String str
    char str[] = "One two       three\n four\tfive ";
    // Print the result
    printf("No of words : %d", countWords(str));
    return 0;
}


C++




// C++ program to count total
// number of words in the string
#include <bits/stdc++.h>
using namespace std;
 
// Function to count total number
// of words in the string
int countWords(string str)
{
  // Check if the string is null
  // or empty then return zero
  if (str.size() == 0) {
    return 0;
  }
  // Splitting the string around
  // matches of the given regular
  // expression
  vector<string> words;
  string temp = "";
  for (int i = 0; i < str.size(); i++) {
    if (str[i] == ' ') {
      words.push_back(temp);
      temp = "";
    }
    else {
      temp += str[i];
    }
  }
 
  int count = 1;
 
  for (int i = 0; i < words.size(); i++) {
    if (words[i].size() != 0)
      count++;
  }
 
  // Return number of words
  // in the given string
  return count;
}
 
int main()
{
 
  // Given String str
  string str = "One two       three\n four\tfive ";
  // Print the result
  cout << "No of words : " << countWords(str);
  return 0;
}
 
// This code is contributed by akashish__


Java




// Java program to count total
// number of words in the string
import java.io.*;
class GFG
{
     
    // Function to count total number
    // of words in the string
    public static int
      countWords(String str)
    {
         
        // Check if the string is null
        // or empty then return zero
        if (str == null || str.isEmpty())
            return 0;
         
        // Splitting the string around
        // matches of the given regular
        // expression
        String[] words = str.split("\\s+");
         
        // Return number of words
        // in the given string
        return words.length;
    }
     
    // Driver Code
    public static void main(String args[])
    {
         
        // Given String str
        String str =
          "One two       three\n four\tfive ";
         
        // Print the result
        System.out.println("No of words : " +
           countWords(str));
    }
}
// This code is contributed by Prashant Srivastava


Python3




# Python program to count total
# number of words in the string
 
 
def countWords(s):
 
    # Check if the string is null
    # or empty then return zero
    if s.strip() == "":
        return 0
 
    # Splitting the string
 
    words = s.split()
 
    return len(words)
 
 
if __name__ == "__main__":
    s = "One two       three\n four\tfive "
    print("No of words : ", countWords(s))


C#




// Include namespace system
using System;
 
 
// C# program to count total
// number of words in the string
public class GFG
{
    // Function to count total number
    // of words in the string
    public static int countWords(String str)
    {
        // Check if the string is null
        // or empty then return zero
        if (str == null || str.Length == 0)
        {
            return 0;
        }
        // Splitting the string around
        // matches of the given regular
        // expression
        String[] words = str.Split(" ");
       
      int count = 1;
       
      for(int i=0;i<words.Length;i++){
          if(words[i].Length!=0) count++;
      }
       
        // Return number of words
        // in the given string
        return count;
    }
    // Driver Code
    public static void Main(String[] args)
    {
        // Given String str
        var str = "One two       three\n four\tfive ";
        // Print the result
        Console.WriteLine("No of words : " + GFG.countWords(str).ToString());
    }
}


Javascript




// Javascript program to count total
// number of words in the string
 
// Function to count total number
// of words in the string
function countWords(str)
{
 
  // Check if the string is null
  // or empty then return zero
  if (str.length == 0) {
    return 0;
  }
   
  // Splitting the string around
  // matches of the given regular
  // expression
  words = [];
  var temp = "";
  for (var i = 0; i < str.length; i++) {
    if (str[i] == " ") {
      words.push(temp);
      temp = "";
    }
    else {
      temp += str[i];
    }
  }
 
  var count = 1;
 
  for (var i = 0; i < words.length; i++) {
    if (words[i].length != 0)
      count++;
  }
 
  // Return number of words
  // in the given string
  return count;
}
 
// Driver code
  // Given String str
  var str = "One two       three\n four\tfive ";
  // Print the result
  console.log("No of words : " +countWords(str));
  
// This code is contributed by Abhijeet Kumar(abhijeet19403)


Output

No of words : 5

Time Complexity: O(N)
Auxiliary Space: O(1)

Method 3:  using StringTokenizer.countTokens() method

  1. Get the string to count the total number of words.
  2. Check if the string is empty or null then return 0.
  3. Create a StringTokenizer with the given string passed as a parameter.
  4. Count the total number of words in the given string using the countTokens() method.
  5. Now, print the result.

Below is the implementation of the above approach:

C




// C program to count total
// number of words in the string
#include <stdio.h>
#include <string.h>
 
// Function to count total number
// of words in the string
int countWords(char* s)
{
    // Check if the string is null
    // or empty then return zero
    if (s == NULL || strlen(s) == 0)
        return 0;
 
    int count = 0;
 
    char* token = strtok(s, "/");
 
    while (token != NULL) {
        ++count;
        token = strtok(NULL, "/");
    }
 
    return count;
}
 
int main()
{
    char str[] = "One/ two /      three/n four/tfive ";
 
    // Print the result
    printf("No of words: %d\n", countWords(str));
 
    return 0;
}


C++




// C++ program to count total
// number of words in the string
#include <bits/stdc++.h>
using namespace std;
 
// Function to count total number
// of words in the string
int countWords(string s)
{
 
    // Check if the string is null
    // or empty then return zero
    if (s.empty())
        return 0;
 
    istringstream is(s);
 
    int count = 0;
 
    string line;
 
    while (getline(is, line, '/'))
        ++count;
 
    return count;
}
int main()
{
    string str = "One/ two /      three/n four/tfive ";
 
    // Print the result
    cout << "No of words: " << countWords(str) << endl;
}


Java




// Java program to count total
// number of words in the string
import java.util.StringTokenizer;
 
class GFG
{
     
    // Function to count total number
    // of words in the string
    public static int
      countWords(String str)
    {
         
        // Check if the string is null
        // or empty then return zero
        if (str    == null || str.isEmpty())
            return 0;
         
        // Create a StringTokenizer with the
        // given string passed as a parameter
        StringTokenizer tokens = new
          StringTokenizer(str);
         
        // Return the number of words
        // in the given string using
        // countTokens() method
        return tokens.countTokens();
    }
     
    // Driver Code
    public static void main(String args[])
    {
         
        // Given String str
        String str =
          "One two       three\n four\tfive ";
         
        // Print the result
        System.out.println("No of words: " +
          countWords(str));
    }
}
// This code is contributed by Prashant Srivastava


Python3




def count_words(s):
    # Check if the string is null or empty then return zero
    if not s:
        return 0
 
    count = 0
    lines = s.split("/")
    for line in lines:
       
        # Ignore empty lines
        if line.strip():
            count += 1
 
    return count
 
s = "One/ two /      three/n four/tfive "
print("No of words:", count_words(s))
 
# This code is contributed by divyansh2212


C#




// C# program to count total
// number of words in the string
using System;
 
class GFG
{
 
  // Function to count total number
  // of words in the string
  public static int
    countWords(String str)
  {
 
    // Check if the string is null
    // or empty then return zero
    if (string.IsNullOrEmpty(str))
      return 0;
 
    // Create a String Token with the
    // given string passed as a parameter
    string[] tokens = str.Split(' ');
 
    // Return the number of words
    // in the given string using
    // Length method
    return tokens.Length;
  }
 
  // Driver Code
  public static void Main()
  {
 
    // Given String str
    string str =
      "One two     three\n four\tfive ";
 
    // Print the result
    Console.Write("No of words: " +
                  countWords(str));
  }
}
 
// This code is contributed by Pushpesh Raj


Javascript




// JavaScript program to count total
// number of words in the string
 
// Function to count total number
// of words in the string
function countWords(s)
{
 
  // Check if the string is null
  // or empty then return zero
  if (s.length === 0) return 0;
  const lines = s.split("/");
  return lines.length;
}
 
const str = "One/ two /      three/n four/tfive ";
 
// Print the result
console.log(`No of words: ${countWords(str)}`);
 
// This code is contributed by akashish__


Output

No of words: 5

Time Complexity: O(N)
Auxiliary Space : O(1)

Method 4: using Character.isLetter() method

  1. Get the string to count the total number of words.
  2. Check if the string is empty or null then return 0.
  3. Converting the given string into a character array.
  4. Check if the character is a letter and index of the character array doesn’t equal to the end of the line that means, it is a word and set isWord by true.
  5. Check if the character is not a letter that means there is a space, then we increment the wordCount by one and set the isWord by false.
  6. Check for the last word of the sentence and increment the wordCount by one.
  7. Now, print the result.

Below is the implementation of the above approach:

C




// C program to count total
// number of words in the string
 
#include <ctype.h>
#include <stdio.h>
 
// Function
// To count total number
// of words in the string
int countWords(char* str, int n)
{
    // Check if the string is null
    // or empty then return zero
    if (n == 0) {
        return 0;
    }
    int wordCount = 0;
    int isWord = 0;
    int endOfLine = n - 1;
 
    for (int i = 0; i < n; i++) {
 
        // Check if the character is a letter
        // and index of character array doesn't
        // equal to end of line that means, it is
        // a word and set isWord by true
        if (isalpha(str[i]) && i != endOfLine) {
            isWord = 1;
        }
 
        // Check if the character is not a letter
        // that means there is a space, then we
        // increment the wordCount by one and set
        // the isWord by false
        else if (!isalpha(str[i]) && isWord)
 
        {
            wordCount++;
            isWord = 0;
        }
 
        // Check for the last word of the
        // sentence and increment the wordCount
        // by one
        else if (isalpha(str[i]) && i == endOfLine) {
            wordCount++;
        }
    }
 
    // Return the total number of
    // words in the string
    return wordCount;
}
 
// Driver code
int main()
{
    char str[] = "One two     three\n four\tfive ";
    int n = (sizeof(str) / sizeof(char)) - 1;
    printf("No of words : %d", countWords(str, n));
    return 0;
}


C++




// C++ program to count total
// number of words in the string
 
#include <bits/stdc++.h>
using namespace std;
 
// Function
// To count total number
// of words in the string
int countWords(char* str, int n)
{
    // Check if the string is null
    // or empty then return zero
    if (n == 0) {
        return 0;
    }
    int wordCount = 0;
    bool isWord = false;
    int endOfLine = n - 1;
 
    for (int i = 0; i < n; i++) {
 
        // Check if the character is a letter
        // and index of character array doesn't
        // equal to end of line that means, it is
        // a word and set isWord by true
        if (isalpha(str[i]) && i != endOfLine) {
            isWord = true;
        }
 
        // Check if the character is not a letter
        // that means there is a space, then we
        // increment the wordCount by one and set
        // the isWord by false
        else if (!isalpha(str[i]) && isWord)
 
        {
            wordCount++;
            isWord = false;
        }
 
        // Check for the last word of the
        // sentence and increment the wordCount
        // by one
        else if (isalpha(str[i]) && i == endOfLine) {
            wordCount++;
        }
    }
 
    // Return the total number of
    // words in the string
    return wordCount;
}
 
// Driver code
int main()
{
    char str[] = "One two     three\n four\tfive ";
    int n = (sizeof(str) / sizeof(char)) - 1;
    cout << "No of words : " << countWords(str, n);
    return 0;
}
 
// This is code is contributed by Aarti_Rathi


Java




// Java program to count total
// number of words in the string
import java.io.*;
class GFG
{
     
    // Function to count total number
    // of words in the string
    public static int
      countWords(String str)
    {
         
        // Check if the string is null
        // or empty then return zero
        if(str    == null || str.isEmpty())
            return 0;
         
        int wordCount = 0;
         
        boolean isWord = false;
        int endOfLine = str.length() - 1;
         
        // Converting the given string
        // into a character array
        char[] ch = str.toCharArray();
         
        for (int i = 0; i < ch.length; i++) {
             
            // Check if the character is a letter
            // and index of character array doesn't
            // equal to end of line that means, it is
            // a word and set isWord by true
            if (Character.isLetter(ch[i])
                && i != endOfLine)
               
                isWord = true;
             
            // Check if the character is not a letter
            // that means there is a space, then we
            // increment the wordCount by one and set
            // the isWord by false
            else if (!Character.isLetter(ch[i])
                     && isWord) {
               
                wordCount++;
                isWord = false;
            }
             
            // Check for the last word of the
            // sentence and increment the wordCount
            // by one
            else if (Character.isLetter(ch[i])
                     && i == endOfLine)
                wordCount++;
        }
         
        // Return the total number of
        // words in the string
        return wordCount;
         
    }
     
    // Driver Code
    public static void main(String args[])
    {
         
        // Given String str
        String str =
          "One two       three\n four\tfive ";
         
        // Print the result
        System.out.println("No of words : " +
          countWords(str));
    }
}
// This code is contributed by Prashant Srivastava


Python3




# Python program to count total
# number of words in the string
 
# Function to count total number
# of words in the string
def countWords(Str):
     
    # Check if the string is null
    # or empty then return zero
    if(Str == None or len(Str) == 0):
        return 0
     
    wordCount = 0
    isWord = False
    endOfLine = len(Str) - 1
     
    # Converting the given string
    # into a character array
    ch = list(Str)
    for i in range(len(ch)):
         
        # Check if the character is a letter
        # and index of character array doesn't
        # equal to end of line that means, it is
        # a word and set isWord by true
        if(ch[i].isalpha() and i != endOfLine):
            isWord = True
         
        # Check if the character is not a letter
        # that means there is a space, then we
        # increment the wordCount by one and set
        # the isWord by false
        elif(not ch[i].isalpha() and isWord):
            wordCount += 1
            isWord = False
         
        # Check for the last word of the
        # sentence and increment the wordCount
        # by one
        elif(ch[i].isalpha() and i == endOfLine):
            wordCount += 1
     
    # Return the total number of
    # words in the string
    return wordCount
 
# Driver Code
 
# Given String str
Str =  "One two       three\n four\tfive "
 
# Print the result
print("No of words :", countWords(Str))
 
# This code is contributed by rag2127


C#




// C# program to count total
// number of words in the string
using System;
public class GFG
{
 
  // Function to count total number
  // of words in the string
  static int countWords(String str)
  {
 
    // Check if the string is null
    // or empty then return zero
    if(str == null)
    {
      return 0;
    }
    int wordCount = 0;
    bool isWord = false;
    int endOfLine = str.Length - 1;
 
    // Converting the given string 
    // into a character array
    char[] ch = str.ToCharArray();
    for (int i = 0; i < ch.Length; i++)
    {
 
      // Check if the character is a letter
      // and index of character array doesn't
      // equal to end of line that means, it is
      // a word and set isWord by true
      if (Char.IsLetter(ch[i]) 
          && i != endOfLine)
      {
        isWord = true;
      }
 
      // Check if the character is not a letter
      // that means there is a space, then we
      // increment the wordCount by one and set
      // the isWord by false
      else if (!Char.IsLetter(ch[i]) 
               && isWord)
 
      {
        wordCount++;
        isWord = false;
      }
 
      // Check for the last word of the 
      // sentence and increment the wordCount 
      // by one
      else if (Char.IsLetter(ch[i])
               && i == endOfLine)
      {
        wordCount++;
      }
    }
 
    // Return the total number of 
    // words in the string
    return wordCount;
  }
 
  // Driver Code
  static public void Main ()
  {
 
    // Given String str
    string str = "One two       three\n four\tfive ";
 
    // Print the result
    Console.WriteLine("No of words : " + countWords(str));
  }
}
 
// This code is contributed by avanitrachhadiya2155


Javascript




<script>
// Javascript program to count total
// number of words in the string
 
// Function to count total number
    // of words in the string
function countWords(str)
{
    // Check if the string is null
        // or empty then return zero
        if(str    == null || str.length==0)
            return 0;
          
        let wordCount = 0;
          
        let isWord = false;
        let endOfLine = str.length - 1;
          
        // Converting the given string
        // into a character array
        let ch = str.split("");
          
        for (let i = 0; i < ch.length; i++) {
              
            // Check if the character is a letter
            // and index of character array doesn't
            // equal to end of line that means, it is
            // a word and set isWord by true
            if (isLetter(ch[i])
                && i != endOfLine)
                
                isWord = true;
              
            // Check if the character is not a letter
            // that means there is a space, then we
            // increment the wordCount by one and set
            // the isWord by false
            else if (!isLetter(ch[i])
                     && isWord) {
                
                wordCount++;
                isWord = false;
            }
              
            // Check for the last word of the
            // sentence and increment the wordCount
            // by one
            else if (isLetter(ch[i])
                     && i == endOfLine)
                wordCount++;
        }
          
        // Return the total number of
        // words in the string
        return wordCount;
}
 
function isLetter(c) {
  return c.toLowerCase() != c.toUpperCase();
}
 
// Driver Code
 
 // Given String str
let str="One two       three\n four\tfive ";
 
// Print the result
document.write("No of words : " +
          countWords(str));
 
// This code is contributed by ab2127
</script>


Output

No of words : 5

Time Complexity: O(N)
Auxiliary Space: O(1) 

RELATED ARTICLES

Most Popular

Recent Comments