Javatpoint Logo
Javatpoint Logo

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

  1. Initialize the string variable str with the input string.
  2. 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.
  3. Iterate through each word in the words array using a for-each loop.
  4. Within the loop, check if the length of the current word is even using the % operator.
  5. If the length is even, print the word using the System.out.println() method.

Implementation

Filename: EvenLengthWords.java

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.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA