How to print even length words in a string in Java

Given a string of strings, write a Java program to print all even-length words in the 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
  • Use the split() method in the String class to break the string into words. It needs to break the string of sentences. So here "" (space) is passed as a parameter. As a result, the words of the string are split and returned as an array of strings
String[] words = str.split(" ");
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);
	}
}

Output:

am
Geek

 

Submit Your Programming Assignment Details