Java Program to Count Words in a Given String
- Java Program to Count Words in a Given String using loop
- Java Program to Count Words in a String using Split Method
Java Program to Count Words in a Given String using loop
We will write a Java program to count the number of words in a given string using the following steps:
- Initialize a variable to store the String for which we want to count the number of words
- Initialize a variable to store the count of words
- Iterate through the input string and count the number of spaces
- Increment the count of words by 1
- Display the count of words in the input string
public class CountWordsInString {
public static void main(String[] args) {
String str = "Hello World Java Programming";
int count = 1;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ' ' && str.charAt(i + 1) != ' ') {
count++;
}
}
System.out.println("Number of words in the string: " + count);
}
}
Number of words in the string: 4Time Complexity: O(n) - where n is the length of the input string as we are iterating through the input string to count the number of words.
Space Complexity: O(1) - as we are using a constant amount of space to store the count of words.
Java Program to Count Words in a String using Split Method
In this method, we will use the split method to count the number of words in a given string. The split method is used to split a string into an array of substrings based on a delimiter. We will use the split method to count the number of words in a given string. We will follow the following steps to count the number of words in a string using the split method:
- Initialize a variable to store the String for which we want to count the number of words
- Initialize a variable to store the count of words
- Split the input string into an array of substrings based on the space delimiter
- Get the length of the array to get the count of words
- Display the count of words in the input string
public class CountWordsInString {
public static void main(String[] args) {
String str = "Hello World Java Programming";
String[] words = str.split(" ");
int count = words.length;
System.out.println("Number of words in the string: " + count);
}
}
Number of words in the string: 4
Time Complexity: O(n) - where n is the length of the input string as we are splitting the input string into an array of substrings.
Space Complexity: O(n) - where n is the length of the input string as we are storing the substrings in an array.
- Recommended Links
- Selenium Interview Questions