The Wayback Machine - https://web.archive.org/web/20240914090516/https://www.geeksforgeeks.org/java-program-to-print-even-length-words-in-a-string/
Open In App

Java program to print Even length words in a String

Last Updated : 18 Mar, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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(" ");
for(String word : words)
{ }
int lengthOfWord = word.length();
  • If the length is even, then print the word.

Below is the implementation of the above approach: 

Java




// 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

Time complexity: O(n) where n is length of given string
Auxiliary Space: O(1)

Approach 2: Using Dynamic Programming:

In this approach, we split the string into words and store the length of each word in an array. Then, we loop through the array and check if the length of each word is even. If it is, we print the word. This approach uses dynamic programming to store the length of each word in an array, which can be reused in subsequent loops, reducing the overall number of calculations. However, in practice, the difference in performance between this approach and the original approach is likely to be negligible.

Here is the DP approach in Java:

Java




class GfG {
    public static void printWords(String s) {
 
        // Split string into words
        String[] words = s.split(" ");
 
        // Create an array to store the length of each word
        int[] wordLengths = new int[words.length];
 
        // Calculate the length of each word and store in the array
        for (int i = 0; i < words.length; i++) {
            wordLengths[i] = words[i].length();
        }
 
        // Check if the length of each word is even and print if true
        for (int i = 0; i < words.length; i++) {
            if (wordLengths[i] % 2 == 0) {
                System.out.println(words[i]);
            }
        }
    }
 
    // Driver code
    public static void main(String[] args) {
 
        String s = "i am Geeks for Geeks and a Geek";
        printWords(s);
    }
}


Output:

am
Geek

Time complexity: O(n) where n is length of given string
Auxiliary Space: O(n) where n is the total number of characters in the input string.



Previous Article
Next Article

Similar Reads

Java Program to Print all Unique Words of a String
Java program to print all unique words present in the string. The task is to print all words occurring only once in the string. Illustration: Input : Welcome to Geeks for Geeks. Output : Welcome to for Input : Java is great.Python is also great. Output : Java Python also Methods: This can be done in the following ways: Using nested loopsUsing MapUs
4 min read
Find all words from String present after given N words
Given a string S and a list lis[] of N number of words, the task is to find every possible (N+1)th word from string S such that the 'second' word comes immediately after the 'first' word, the 'third' word comes immediately after the 'second' word, the 'fourth' word comes immediately after the 'third' word and so on. Examples: Input: S = “Siddhesh i
11 min read
Print Words with Prime length from a Sentence
+ Given a string S, the task is to print all words with prime length in the given string. Examples: Input: S = "This is a python programming language"Output: isprogrammingExplanation: Length of is is 2 and length of programming is 11 both are primes Input: S = "You are using geeksforgeeks"Output: Youareusinggeeksforgeeks Recommended PracticePlease
15+ min read
Print even positioned nodes of even levels in level order of the given binary tree
Given a binary tree, print even positioned nodes of even level in level order traversal. The root is considered at level 0, and the left most node of any level is considered as a node at position 0. Examples: Input: 1 / \ 2 3 / \ \ 4 5 6 / \ 7 8 / \ 9 10 Output: 1 4 6 9 Input: 2 / \ 4 15 / / 45 17 Output: 2 45 Approach: To print nodes level by leve
8 min read
Lexicographically smallest permutation of a string that can be reduced to length K by removing K-length prefixes from palindromic substrings of length 2K
Given a binary string str of length N, and an integer K, the task is to find the lexicographically smallest permutation of the string str that can be reduced to length K by removal of every K-length prefix from palindromic substrings of length 2K. If no such permutation exists, print "Not Possible". Examples: Input: str = "0000100001100001”, K = 4O
14 min read
Count words that appear exactly two times in an array of words
Given an array of n words. Some words are repeated twice, we need to count such words. Examples: Input : s[] = {"hate", "love", "peace", "love", "peace", "hate", "love", "peace", "love", "peace"}; Output : 1 There is only one word "hate" that appears twice Input : s[] = {"Om", "Om", "Shankar", "Tripathi", "Tom", "Jerry", "Jerry"}; Output : 2 There
6 min read
Check if a string contains a palindromic sub-string of even length
S is string containing only lowercase English alphabets. We need to find if there exists at least one palindromic sub-string whose length is even. Examples: Input : aassssOutput : YESInput : gfgOutput : NOApproach: Approach to solve this problem is to check all even-length substrings of the given string and check if any of them is a palindrome. Thi
8 min read
Length of longest Palindromic Subsequence of even length with no two adjacent characters same
Given a string str, the task is to find the length of the longest palindromic subsequence of even length with no two adjacent characters same except the middle characters. Examples: Input: str = "abscrcdba" Output: 6 Explanation: abccba is the required string which has no two consecutive characters same except the middle characters. Hence the lengt
11 min read
Reduce given array by replacing subarrays of length at least K consisting of even numbers with their length
Given an array arr[] of length N, the task is to replace all subarrays of only even elements by their length if the length is greater than or equal to K. Examples: Input: arr[] = {3, 6, 10, 2, 7, 6, 4, 8}, K = 2Output: 3 3 7 3Explanation: There are two subarrays with consecutive even numbers {6, 10, 2} and {6, 4, 8}. So they are replaced by their l
6 min read
Number of ways to cut a stick of length N into in even length at most K units long pieces
Given a rod of length N units, the task is to find the number of ways to cut the rod into parts such that the length of each part is even and each part is at most K units. Examples: Input: N = 6, K = 4 Output: 3 Explanation: Rod of length 6 units needs to be into parts having length at most 4 units. Hence cut the rod in three ways: Way 1: 2 units +
9 min read
Java Program To Check Whether The Length Of Given Linked List Is Even Or Odd
Given a linked list, the task is to make a function which checks whether the length of the linked list is even or odd. Examples: Input : 1-&gt;2-&gt;3-&gt;4-&gt;NULL Output : Even Input : 1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;NULL Output : OddRecommended: Please solve it on "PRACTICE" first, before moving on to the solution. Method 1: Count the codes linea
3 min read
Java Program to Find the Occurrence of Words in a String using HashMap
HashMap&lt;Key, Value&gt; provides the basic implementation of the Map interface of Java and import java.util.HashMap package or its superclass. HashMap stores the data in (Key, Value) pairs, and accessed by an index of another type (e.g. an Integer). One object is used as a key to another object. If the duplicate key is inserted, it will replace t
3 min read
Java Program to Swap Corner Words and Reverse Middle Characters of a String
Given a string containing n numbers of words. The task is to swap the corner words of the string and reverses all the middle characters of the string. Input: "Hello this is the GFG user" Output: "user GFG eth si siht Hello" Input: "Hello Bye" Output: "Bye Hello" Methods: Using the concept of ASCII valuesUsing the split() method Method 1: Using the
5 min read
Java Program To Reverse Words In A Given String
Example: Let the input string be "i like this program very much". The function should change the string to "much very program this like i" Examples: Input: s = "geeks quiz practice code" Output: s = "code practice quiz geeks" Input: s = "getting good at coding needs a lot of practice" Output: s = "practice of lot a needs coding at good getting" Rec
4 min read
Java Program to Print the Elements of an Array Present on Even Position
The task is to print all the elements that are present in even position. Consider an example, we have an array of length 6, and we need to display all the elements that are present in 2,4 and 6 positions i.e; at indices 1, 3, 5. Example: Input: [1,2,3,4,5,6] Output: 2 4 6 Input: [1,2] Output: 2 Approach:1) First take a class with the name DisplayEl
2 min read
Print all funny words in a string
We are given a sentence. Our task is to print all funny words/strings in that sentence. What is a funny word ? Reverse the given string. Iterate through each character of that string, compare the absolute difference in the ASCII values of the characters at positions 0 and 1, 1 and 2, 2 and 3 and so on to the end. If the list of absolute differences
5 min read
Print words of a string in reverse order
Let there be a string say "I AM A GEEK". So, the output should be "GEEK A AM I" . This can done in many ways. One of the solutions is given in Reverse words in a string . Examples: Input : I AM A GEEK Output : GEEK A AM I Input : GfG IS THE BEST Output : BEST THE IS GfG This can be done in more simpler way by using the property of the "%s format sp
10 min read
Print all unique words of a String
Write a function that takes a String as an argument and prints all unique words in it. Examples: Input: Java is great. Grails is also greatOutput: Java Grails also Approach: The idea is to use the map to keep track of words already occurred. But first, we have to extract all words from a String, as a string may contain many sentences with punctuati
7 min read
Java ArrayList to print all possible words from phone digits
Given a keypad of a mobile, and keys that need to be pressed, the task is to print all the words which are possible to generate by pressing these numbers. Examples: Input: str = "12" Output: [ad, bd, cd, ae, be, ce, af, bf, cf] Explanation: The characters that can be formed by pressing 1 is a, b, c and by pressing 2 characters d, e, f can be formed
4 min read
Minimize steps to form string S from any random string of length K using a fixed length subsequences
Given a string S consisting of N characters and a positive integer K, the task is to find the minimum number of operations required to generate the string S from a random string temp of size K and inserting the subsequence of any fixed length from the random string in the random string. If it is impossible to generate the string S, then print "-1".
12 min read
Sum of Array Divisible by Size with Even and Odd Numbers at Odd and Even Index in Java
Given an array arr[] of size N, Convert the given array as even numbers in the array occurs at the odd index, odd numbers in the array occur at the even index, and whether the sum of the numbers in an array is divisible by the size of an array. If the array follows all the properties then an array is valid else it is invalid. An array will be valid
3 min read
Maximum even length sub-string that is permutation of a palindrome
Given string [Tex]str [/Tex], the task is to find the maximum length of the sub-string of [Tex]str [/Tex]that can be arranged into a Palindrome (i.e at least one of its permutation is a Palindrome). Note that the sub-string must be of even length. Examples: Input: str = "124565463" Output: 6 "456546" is the valid sub-string Input: str = "122313" Ou
9 min read
Check if a string can be split into even length palindromic substrings
Given a string str, the task is to check if it is possible to split the given string into even length palindromic substrings. Examples: Input: str = "abbacc" Output: Yes Explanation: Strings "abba" and "cc" are the even length palindromic substrings.Input: str = "abcde" Output: No Explanation: No even length palindromic substrings possible. Approac
6 min read
Maximum length of string formed by concatenation having even frequency of each character
Given N strings, print the maximum length of the string and the string formed by concatenating any of the N strings, such that every letter in the string occurs even number of times Example: Input: N = 5, str = ["ABAB", "ABF", "CDA", "AD", "CCC"]Output: ABABCDAADCCC 12Explanation: The string formed by concatenation is ABABCDAADCCC. Each letter in t
7 min read
Find the first maximum length even word from a string
Given a string of words separated by spaces. The task is to find the first maximum length even word from the string. Eg: “You are given an array of n numbers” The answer would be “an” and not “of” because “an” comes before “of”.Examples: Input: "this is a test string"Output: stringEven length words are this, is, test, string. Evenmaximum length wor
11 min read
Minimize a binary string by repeatedly removing even length substrings of same characters
Given a binary string str of size N, the task is to minimize the length of given binary string by removing even length substrings consisting of sam characters, i.e. either 0s or 1s only, from the string any number of times. Finally, print the modified string. Examples: Input: str ="101001"Output: "10"Explanation: The string can be minimized in the
8 min read
Count ways to split string into K Substrings starting with even digit and min length M
Given a string S of length N consisting of digits from '0' to '9' .The task is to determine the total number of possible ways to partition the string into K substrings such that : Each substring has a minimum length of M (M&gt;=2).Substring must start with an even digit number and end with an odd digit number.Examples: Input: N = 9, M = 2, k = 3, S
15+ min read
Javascript Program To Check Whether The Length Of Given Linked List Is Even Or Odd
Given a linked list, the task is to make a function which checks whether the length of the linked list is even or odd. Examples: Input : 1-&gt;2-&gt;3-&gt;4-&gt;NULLOutput : EvenInput : 1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;NULLOutput : OddMethod 1: Count the codes linearly Traverse the entire Linked List and keep counting the number of nodes. As soon as t
3 min read
Program to extract words from a given String
The task is to extract words from a given string. There may be one or more space between words. Examples: Input : geeks for geeks Output : geeks for geeks Input : I love coding. Output: I love coding We have discussed a solution in the below post. How to split a string in C/C++, Python and Java? In this post, a new solution using stringstream is di
3 min read
Javascript Program To Reverse Words In A Given String
Example: Let the input string be "i like this program very much". The function should change the string to "much very program this like i" Examples:  Input: s = "geeks quiz practice code" Output: s = "code practice quiz geeks" Input: s = "getting good at coding needs a lot of practice" Output: s = "practice of lot a needs coding at good getting" Al
4 min read
Practice Tags :