1. Introduction
In Java, counting the number of words in a string is a common task. This can be done using various methods, one of which is by splitting the string into an array of words based on spaces, and then counting the number of elements in the array. In this blog post, we will explore a Java program that counts the number of words in a given string.
2. Program Steps
1. Define a main method to serve as the entry point of the program.
2. Initialize a string variable with the text for which we want to count the words.
3. Call a method countWords and pass the string to it.
4. In the countWords method, split the string into an array using the split method and a space as the delimiter.
5. Return and print the length of the array, which represents the number of words in the string.
3. Code Program
public class WordCount {
public static void main(String[] args) {
// Step 2: Initialize a string variable
String text = "Java is a versatile programming language";
// Step 3: Call countWords method and print the result
System.out.println("Number of words in the string: " + countWords(text));
}
public static int countWords(String str) {
// Step 4: Split the string into an array of words
String[] words = str.split("\\s+");
// Step 5: Return the length of the array
return words.length;
}
}
Output:
Number of words in the string: 5
4. Step By Step Explanation
– Step 1: The main method is defined as the program's starting point.
– Step 2: A string variable text is initialized with the text whose words we want to count.
– Step 3: We call the countWords method, passing the text string as an argument, and print the result.
– Step 4: Inside the countWords method, the string is split into an array of words using the split method and a space (\\s+) as the delimiter.
– Step 5: The length of the array words, representing the number of words in the string, is returned and printed.
This program demonstrates a simple and efficient way to count the number of words in a string in Java.