I need to find a word in a string that is both the longest as well as even. A few examples:
The sentence Time to construct great art. This should return the string time because it is the greatest even length word, with the length being 4, it is not construct because construct is length 9 which is odd.
Also, in the example of Time to write great code. This should return the string Time, because it is even, and has a even length of 4. It will not return the word code because Time occurs first.
String[] array = sentence.split(" "); String longestWord = " "; for (int i = 0; i < array.length; i ++) { if (array[i].length() >= longestWord.length()) { longestWord = array[i]; } } System.out.println(longestWord); My code successfully prints the longest word, however does not take into account whether the longest strings length is even and if it occurs first.
I have tried using some modulus characters in my for loop, but it is not tracking whether or not the greatest word is even, if not, move to next greatest word.
Also, I am having a hard time tracking if the word comes first or not.
What I've tried for accounting for even:
for (int i = 0; i < array.length; i ++) { if (array[i].length() >= longestWord.length()) { longestWord = array[i]; if (longestWord.length() % 2 != 0) { break; } else { longestWord = array[i]; } } }
Pattern.compile("\\p{L}+").matcher(input).results().map(MatchResult::group).filter(s -> (s.length() & 1) == 0).max(Comparator.comparing(String::length)).orElse(" ")