0

Ok first, please don't mark this down as a duplicate question. I know there are similar questions that explain it with specific strings, I need a "generic code" so to speak. I know how to do this with a given array, but I'm not sure how to do it for this assignment. It wants me to return the longest word in an array that is not present. But if for example there was an array of ["dog", "ostrich", "eagle"], it would return "ostrich".

public class Longest {
    public static String longWord(String[] word) {
        int array[] = [];
        for (int i = 0; i < array.length; i++) {
            if (word > current) {
                return longWord;
            }
        }
    }
}
ThatBoy123
  • 77
  • 1
  • 11

3 Answers3

1

You can use Stream.max(Comparator) method for this:

String[] arr = {"dog", "ostrich", "eagle"};

String max = Arrays.stream(arr)
        .max(Comparator.comparingInt(String::length))
        .orElse(null);

System.out.println(max); // ostrich

See also: First unique character in a string using LinkedHashMap

0

Loop through the words and If the current word have more length than previous word,then make longest word as current word.So at the end you will get longest word.

public class Longest {
    public static String longWord(String[] words) {
        //assume initially the longest word is an empty String
        String longestWord = "";
        //loop through each word
        for (String word: words) {
            //check if the each items length with previous largest length
            if (word.length() > longestWord.length()) {
                //make longest word as current if it matches the condition
                longestWord = word;
            }
        }
        //return the longest word,if word array is empty it return empty String
        return longestWord;
    }
}

Or Use the Array sort method to find the largest element as follows

public class Longest {
    public static String longWord(String[] word) {
        //sort the array based on the length,So that
        // largest element will be at the end of the array
        Arrays.sort(word, Comparator.comparing(String::length));
        //return the last element
        return word[word.length-1];
    }
}
Jinesh Francis
  • 3,377
  • 3
  • 22
  • 37
-3

Find the length of the string array first, then loop through it finding the length of each word using strlen(). Keep two variables one for max length and one for the index of longest string, return str[index].

Abra
  • 19,142
  • 7
  • 29
  • 41