June 14, 2024

JaiHoDevs

Java program to count the number of words present in a string

Write a Java program to count the number of words present in a string?

Sure, here's a simple Java program that counts the number of words in a given string:


Program:

  public class Test 
{
    public static void main (String args[])
    {
        String s = "Sharma is a good player and he is so punctual";
        String words[] = s.split(" ");
        System.out.println("The Number of words present in the string are : "+words.length);
    }
}

Output

The Number of words present in the string are : 10


import java.util.Scanner;

public class WordCount {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        System.out.println("Enter a string:");
        String input = scanner.nextLine();
        
        int wordCount = countWords(input);
        
        System.out.println("Number of words: " + wordCount);
        
        scanner.close();
    }
    
    public static int countWords(String input) {
        if (input == null || input.isEmpty()) {
            return 0;
        }
        
        String[] words = input.split("\\s+");
        return words.length;
    }
}


This program prompts the user to enter a string, then it counts the number of words in the input string using the countWords method. The countWords method splits the input string by one or more whitespace characters using the split method, then returns the length of the resulting array, which represents the number of words in the string.

Subscribe to get more Posts :