Count numbers of spaces and number of words from the input string


 

Count numbers of spaces and number of words from the input string

In this section, you will learn how to count the number of spaces and words from the string.

In this section, you will learn how to count the number of spaces and words from the string.

Count numbers of spaces and number of words from the input string Java

In this section, you will learn how to count the number of spaces and words from the string. For this purpose, we have prompted the user to enter the string. The scanner class reads the string from the console. After initializing a counter, we have created a condition that if any white space character is found throughout the string length, the counter is incremented by 1. This counter determines the number of spaces. Now, in order to count the number of words, we have splitted the string into string array using split() method and determines the number of words.

Here is the code of CountSpaces.java:

import java.util.*;

public class CountSpaces
{
public static void main (String[] args)
{
System.out.print ("Enter a sentence or phrase: ");
Scanner input=new Scanner(System.in);
String str=input.nextLine();
int count = 0;
int limit = str.length();
for(int i = 0; i < limit; ++i)
{
    if(Character.isWhitespace(str.charAt(i)))
    {
         ++count;
    }
}
System.out.println("Number of spaces :"+count);
String[] words = str.split(" ");  
int numwords = words.length;  
System.out.println("Number of words :"+numwords);
}
}

Output:

Enter a sentence or phrase: Java is a programming language.
Number of spaces :4
Number of words :5

Ads