Word Count

Word Count

Problem Description

Given a string A. The string contains some words separated by spaces.
Return the number of words in the given string.

Problem Constraints

1 <= |A| <= 105
Ai = { lowercase English letters or spaces}

Input Format

The first and only argument is a string A.

Output Format

Return an integer.

Example Input

Input 1:

A = "bonjour"

Input 2:

A = "hasta la vista"

Example Output

Output 1:

1

Output 2:

3

Example Explanation

Explanation 1:

The string has only one word "bonjour".

Explanation 2:

The string have three words "hasta", "la", "vista".

Problem Solution:

Language Used: Java

Approach1: Using StringTokenizer (1 Line Code)

public class Solution 
{
    public int solve(String A) 
    {
        StringTokenizer st = new StringTokenizer(A," ");
        return st.countTokens();
    }
}

Approach2:

public class Solution 
{
    public int solve(String A) 
{
        A = A.trim(); // removing all the extra space from font and back
        if(A.length() == 0)
        { // for cases where the string is empty
            return 0;
        }
        String[] str = A.split("\\s+" ,0);// splitting the array with      whitespace as delimiter

        return str.length; // number of words
    }
}

Approach3:

public class Solution 
{
    public int solve(String A) 
{
        int c=0;

        boolean x=false;

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

        {

            if(A.charAt(i)==' ' && x==true)

            {

                c++;

                x=false;

            }

            else if((int)A.charAt(i)!=32)

            {

                x=true;

            }
        }

        if(A.length()>0 && x!=false)

        return c+1;

        return c;
    }
}

THANK YOU !!!