0

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]; } } } 
2
  • To fix your longest word coming first error you should take a look at how you are comparing lengths. I don't want to spell it out completely just yet as this seems like a learning exercise and I want you to find the answer on your own but ping back if you are struggling. Commented Apr 9, 2019 at 19:21
  • Pattern.compile("\\p{L}+").matcher(input).results().map(MatchResult::group).filter(s -> (s.length() & 1) == 0).max(Comparator.comparing(String::length)).orElse(" ") Commented Apr 9, 2019 at 20:07

9 Answers 9

3

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 
Sign up to request clarification or add additional context in comments.

Comments

1

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

4 Comments

Welcome @JohnEgg
This won't work on input "I am good." since it will result into "am" instead of "good". Generally on inputs where the longest even word is located before a punctuation mark.
@JohnEgg if you have to consider this, better to go regex approach. I will update the answer soon
@JohnEgg I have updated the answer with Regex, check
0

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.

1 Comment

Thank you this really helped!
0
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); } } 

3 Comments

please explain the logic and add comments to the code to highlight the logic.
@Anand vidvat - simply split the sentence using split function where Delimiter is space.. After splitting we will be having array of words. Iterate the array using for loop & check for length of each word.. I have used modulo operator to check if length is even I.e. remainder should be zero. Now check if the length of previous word is smaller than the length of current word. If true then update the value of Len variable because we need to find Maximum length.. At the end return the result
could you add this to your answer to make it more understandable.
0

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); 

}

Comments

0
public class LongestEvenString { public static void main(String[] args) { String test = "this is a sample input for the problem"; System.out.println(longestEvenString(test)); } public static String longestEvenString(String test) { // Splits a sentence to array of Strings. String[] words = test.split(" "); // curlen stores length of current word in string Array // maxlen stores length of maximum_length word in string Array int curlen = 0; int maxlen = 0; String output = ""; for (String word:words) { curlen = word.length(); // loop runs only if length of the current word is more than // maximum_length thus excluding future same maximum_length words. // and also checks for even_length of that word if(curlen > maxlen && curlen%2 == 0){ maxlen = curlen; output = word; } } // returns maximum_even_length word which occurred first return output; } } 

Comments

0

public class FindLongestEvenWord {

public static void main(String[] args) { String s = "Be not afraid of greatness some are born great some achieve greatness"; List<String> strList = Arrays.asList(s.trim().split(" ")); Optional<String> maxLengthEvenWord = strList.stream().filter(s3->s3.length()%2==0).reduce((s1,s2)->s1.length()>s2.length()?s1:s2); if(maxLengthEvenWord.isPresent()) System.out.println(maxLengthEvenWord.get()); } 

}

1 Comment

Please post with code block properly. And also try to explain in few words
0
String sentence = "Time to construct great art"; String[] array = sentence.split(" "); String longestWord = " "; for (int i = 0; i < array.length; i ++) { if (array[i].length() >= longestWord.length()) { if (array[i].length() % 2 == 0) { longestWord = array[i]; } } } System.out.println(longestWord); 

Comments

-1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.