How many words HackerRank solution in python

PythonServer Side ProgrammingProgramming

In this article, we will learn about the solution to the problem statement given below.

Problem statement − We are given a string we need to count the number of words in the string

Approach 1 − Using split() function

Split function breaks the string into a list iterable with space as a delimiter. if the split() function is used without specifying the delimiter space is allocated as a default delimiter.

Example

 Live Demo

test_string = "Tutorials point is a learning platform" #original string print ("The original string is : " + test_string) # using split() function res = len(test_string.split()) # total no of words print ("The number of words in string are : " + str(res))

Output

The original string is : Tutorials point is a learning platform The number of words in string are : 6

Approach 2 − Using regex module

Here findall() function is used to count the number of words in the sentence available in a regex module.

Example

 Live Demo

import re test_string = "Tutorials point is a learning platform" # original string print ("The original string is : " + test_string) # using regex (findall()) function res = len(re.findall(r'\w+', test_string)) # total no of words print ("The number of words in string are : " + str(res))

Output

The original string is: Tutorials point is a learning platform The number of words in string is: 6

Approach 3 − Using sum()+ strip()+ split() function

Here we first check all the words in the given sentence and add them using the sum() function.

Example

 Live Demo

import string test_string = "Tutorials point is a learning platform" # printing original string print ("The original string is: " + test_string) # using sum() + strip() + split() function res = sum([i.strip(string.punctuation).isalpha() for i in test_string.split()]) # no of words print ("The number of words in string are : " + str(res))

Output

The original string is : Tutorials point is a learning platform The number of words in string are : 6

All the variables are declared in the local scope and their references are seen in the figure above.

Conclusion

In this article, we have learned how to count the number of words in the sentence.

How many words HackerRank solution in python

Updated on 11-Jul-2020 11:33:33

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. 



unsigned countWords(char *str) 

        if (*str == ' ' || *str == '\n' || *str == '\t') 

    char str[] = "One two     three\n four\tfive "; 

    cout<<"No of words : "<<countWords(str); 

unsigned countWords(char *str)

        if (*str == ' ' || *str == '\n' || *str == '\t')

    char str[] = "One two         three\n    four\tfive  ";

    printf("No of words : %u", countWords(str));

    static final int OUT = 0;

    static int countWords(String str)

            if (str.charAt(i) == ' ' || str.charAt(i) == '\n' 

                    || str.charAt(i) == '\t')

    public static void main(String args[])

        String str = "One two       three\n four\tfive  ";

        System.out.println("No of words : " + countWords(str));

    for i in range(len(string)):

        if (string[i] == ' ' or string[i] == '\n' or

string = "One two         three\n four\tfive "

print("No. of words : " + str(countWords(string)))

    static int countWords(String str)

            if (str[i] == ' ' || str[i] == '\n'|| 

    public static void Main()

        String str = "One two     three\n four\tfive ";

        Console.WriteLine("No of words : "

function countWords($str)

    while ($i < strlen($str))

$str = "One two         three\n four\tfive ";

echo "No of words : " . countWords($str);

    function countWords( str)

            if (str[i] == ' ' || str[i] == '\n'|| 

        var str = "One two     three\n four\tfive ";

        document.write("No of words : "

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:

        if (str == null || str.isEmpty())

        String[] words = str.split("\\s+");

    public static void main(String args[])

          "One two       three\n four\tfive ";

        System.out.println("No of words : " +

if __name__ == "__main__":

    s = "One two       three\n four\tfive "

    print("No of words : ", countWords(s))

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:

import java.util.StringTokenizer;

        if (str    == null || str.isEmpty())

        StringTokenizer tokens = new 

        return tokens.countTokens();

    public static void main(String args[])

          "One two       three\n four\tfive ";

        System.out.println("No of words: " +

Time Complexity: O(N)

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:

int countWords(char* str, int n)

    for (int i = 0; i < n; i++) {

        if (isalpha(str[i]) && i != endOfLine) {

        else if (!isalpha(str[i]) && isWord)

        else if (isalpha(str[i]) && i == endOfLine) {

    char str[] = "One two     three\n four\tfive ";

    int n = (sizeof(str) / sizeof(char)) - 1;

    cout << "No of words : " << countWords(str, n);

        if(str    == null || str.isEmpty())

        int endOfLine = str.length() - 1;

        char[] ch = str.toCharArray();

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

            if (Character.isLetter(ch[i]) 

            else if (!Character.isLetter(ch[i]) 

            else if (Character.isLetter(ch[i])

    public static void main(String args[])

          "One two       three\n four\tfive ";

        System.out.println("No of words : " +

    if(Str == None or len(Str) == 0):

        if(ch[i].isalpha() and i != endOfLine):

        elif(not ch[i].isalpha() and isWord):

        elif(ch[i].isalpha() and i == endOfLine):

Str =  "One two       three\n four\tfive "

print("No of words :", countWords(Str))

  static int countWords(String str)

    int endOfLine = str.Length - 1; 

    char[] ch = str.ToCharArray(); 

    for (int i = 0; i < ch.Length; i++)

      else if (!Char.IsLetter(ch[i])  

      else if (Char.IsLetter(ch[i]) 

  static public void Main ()

    string str = "One two       three\n four\tfive ";

    Console.WriteLine("No of words : " + countWords(str)); 

        if(str    == null || str.length==0)

        let endOfLine = str.length - 1;

        for (let i = 0; i < ch.length; i++) {

            else if (!isLetter(ch[i])

  return c.toLowerCase() != c.toUpperCase();

let str="One two       three\n four\tfive ";

document.write("No of words : " +

Time Complexity: O(N)

Auxiliary Space: O(1)
 


Article Tags :

Practice Tags :