How to count the number of words in a given string sentence ?

How to count the number of words in a given string sentence ?

Program
import java.util.Scanner;
public class Main
{
	public static void main(String[] args) 
	{
		int x,count=1;
		String s;
		Scanner sc=new Scanner(System.in);
		System.out.println("Enter String :");
		s=sc.nextLine();
		for (x = 0; x < s.length(); x++) 
		{
            if (s.charAt(x) == ' ') 
            {
                count++;
            }
        }
		System.out.println("Number of words are : "+count);
	}

}

Output:

Enter String : Welcome to MSK Technologies
Number of words are : 4





More Questions


18 . How to check if a string is a palindrome?
19 . How to count the number of words in a given string sentence?
20 . How to reverse the words from the given string sentence?
21 . How to swap two strings without using the third variable?