Given a string str, write a Java program to print all words with even length in the given string.
Examples:
Input: s = "This is a java language"
Output: This
is
java
language
Input: s = "i am GFG"
Output: am
Approach:
- Take the string
- Break the string into words with the help of split() method in String class. It takes the string by which the sentence is to be broken. So here ” “(space) is passed as the parameter. As a result, the words of the string are split and returned as a string array
String[] words = str.split(" "); - Traverse each word in the string array returned with the help of Foreach loop in Java.
for(String word : words) { } - Calculate the length of each word using String.length() function.
int lengthOfWord = word.length();
- If the length is even, then print the word.
Below is the implementation of the above approach:
// Java program to print // even length words in a string class GfG { public static void printWords(String s) { // Splits Str into all possible tokens for (String word : s.split(" ")) // if length is even if (word.length() % 2 == 0) // Print the word System.out.println(word); } // Driver Code public static void main(String[] args) { String s = "i am Geeks for Geeks and a Geek"; printWords(s); } } |
chevron_right
filter_none
Output:
am Geek
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- C program to print the length of a String using %n format specifier
- Java Program to print all permutations of a given string
- Program to print the given digit in words
- Print all unique words of a String
- Print all funny words in a string
- Java Program to print distinct permutations of a string
- Java program to print all duplicate characters in a string
- Print words of a string in reverse order
- Extract and print words separately from a given Camel Case string
- Program to extract words from a given String
- Program to reverse words in a given string in C++
- Java ArrayList to print all possible words from phone digits
- Reverse words in a given String in Java
- Print string of odd length in 'X' format
- Java program to swap first and last characters of words in a sentence
- Check if the given string of words can be formed from words present in the dictionary
- Program for length of a string using recursion
- Program to print all substrings of a given string
- Write a program to print all permutations of a given string
- How to determine length or size of a String in Java?
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

