'How to find longest word in string that is even

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];
                }
            }
        }


Solution 1:[1]

You can use the modulo operator (%) to check if the string length is even:

string.length() % 2 == 0

To complete that you can use Arrays.stream() to find the longest string with even length:

String longestWord = Arrays.stream(sentence.split(" ")) // creates the stream with words
        .filter(s -> s.length() % 2 == 0) // filters only the even length strings
        .max(Comparator.comparingInt(String::length)) // finds the string with the max length
        .orElse(" "); // returns " " if none string is found

Solution 2:[2]

The changes are that you compare the > from the longest length and not >= and check is the length is even.

To accommodate the cases where there are other symbols like '.', use Regex patterns.

public static void main(String[] args) {
    // TODO Auto-generated method stub

    String input = "I am good.";
    String[] input_words = input.split(" ");
    String longestWord = " ";

    for(String word : input_words) {
        Pattern p = Pattern.compile("^[a-zA-Z]+");
        Matcher m = p.matcher(word);
        m.find();
        if(m.group().length() % 2 == 0 && m.group().length() > longestWord.length()) {
            longestWord = m.group();
        }
    }
    System.out.println("result : " + longestWord);
}

This will print the largest first occurring even word

Solution 3:[3]

Using the % (modulus) operator is a common way of evaluating whether a number is odd or even by inspecting whether dividing by 2 elicits a remainder. You would use it here like so:

if (array[i].length() >= longestWord.length() && array[i].length() % 2 == 0) {
                longestWord = array[i];
         }

edit: I feel bad because this sounds like an assignment, so I won't solve the "coming first" part of the problem.

Solution 4:[4]

public class HelloWorld {

     public static void main(String []args) {

        String sentence = "this is a sample input for the problem";
        
        String arr[] = sentence.split("\\s+"); // to split the sentence by space (because words are separated by space) 
        
        int len =  0; 
        String word = "";
        for (int i= 0; i< arr.length; i++) {
            if((arr[i].length())%2 == 0) { // check if the length of the word is even 
                int len1 = arr[i].length();
                if (len1 > len ) { // if new length is greater than the previous word's length then assign the value of new length to len variable
                    len = len1;
                    word = arr[i];  // word = highest length word
                }
            }
        }
        System.out.println(word);
     }
}

Solution 5:[5]

The solution to the question in python is:

def longestevenword(sentence):
  #converting the sentence into lists
  string_list = sentence.split()
  size = 0
  #iteration through each word in the list
  for word in string_list:
    #check to see if the word has even number of characters
    if len(word)%2 == 0:
      #checking if the length of the of the word
      if size <= len(word):
        size = len(word)
        even_word = word
    else:
      continue        
  # printing the longest even word in a given sentence.
  print(even_word)


## function call to test
longestevenword("This is a cat that had a puppyy")

Output: puppyy

It's also available on my GitHub https://github.com/jaikishpai/CommonSolutions/blob/main/LongestEvenWord.py

Solution 6:[6]

public static void main(String[] args) { // TODO Auto-generated method stub

String input = "I am good.";
String[] input_words = input.split(" ");
String longestWord = " ";

for(String word : input_words) {
    Pattern p = Pattern.compile("^[a-zA-Z]+");
    Matcher m = p.matcher(word);
    m.find();
    if(m.group().length() % 2 == 0 && m.group().length() > longestWord.length()) {
        longestWord = m.group();
    }
}
System.out.println("result : " + longestWord);

}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 brandonx
Solution 4 EricSchaefer
Solution 5 cigien
Solution 6 Anilkumar