Java Program to Print Even Length Words in a String
Given a string str, write a Java program to print all words with even length in the given string.
Example 1:
Input: t= She sells seashells by the seashore
Output:
By
Seashore
Example 2:
Input: t= To be or not to be, that is the question
Output:
To
be
or
to
that
is
question
Approach: Using split() method
The split() method is a built-in Java method used to split a string into an array of substrings based on a specified delimiter. In Java programming, the split() method is a commonly employed technique for manipulating and handling string data. It can perform various tasks, such as searching for specific patterns, removing unwanted characters, and extracting data from a string.
Algorithm
- Initialize the string variable str with the input string.
- To split a string into an array of words in Java, use the split() method with a specified delimiter and store the resulting substrings in an array. It enables the manipulation and analysis of individual words within the string.
- Iterate through each word in the words array using a for-each loop.
- Within the loop, check if the length of the current word is even using the % operator.
- If the length is even, print the word using the System.out.println() method.
Implementation
Filename: EvenLengthWords.java
public class EvenLengthWords { public static void main(String[] args) { String str = " She sells seashells by the seashore "; // Splitting the string into an array of words String[] words = str.split(" "); // Iterating through the words and printing even length words for(String word : words) { if(word.length() % 2 == 0) { System.out.println(word); } } } }
Output:
by seashore
Complexity Analysis:
Time complexity: Splitting the string into words using the split() method takes O(n) time, where n is the length of the input string. Iterating through the array of words and checking if each word has an even length also takes O(n) time. Printing each even-length word takes O(1) time.
Space complexity: The code uses an array of words to store the individual words of the input string. The size of the array is proportional to the number of words in the string, which can be at most n/2, where n is the length of the input string. Therefore, the space complexity of the array is O(n). The space complexity of the remaining variables and data structures used in the program is constant and can be ignored.