Dee
Dee

Reputation: 145

Finding the longest string in an array of Strings

The problem with this is that i tried to do it but my method to check the length of the string is not working; what can I do to fix it?

public static void main(String[] args) { 
    String[] animalNames = {"cat", "rabbit", "horse", "goat", "rooster", "ooooooooooooooo"};
    String a= getLongestString(animalNames);
    System.out.println(a);
}

public static String getLongestString(String []animalNames) {
  //  String animalNames[] =  {"cat","chicken","horse","ooooooooo" };

    int j = 0;
    for (j = 0; j <= animalNames.length; j++) {
        if (animalNames[j].length() > animalNames[j + 1].length()) {
                return (animalNames[j]);
            }
        }
        return null;
    }

}

Upvotes: 12

Views: 89016

Answers (5)

Nestor Milyaev
Nestor Milyaev

Reputation: 6595

It's real simple using java 8+ (just check that your array is not empty first or process the .get() specially):

List<String> strings = Arrays.asList(animals);    
String longest = strings.stream().
    max(Comparator.comparingInt(String::length)).get();
int max = longest.length();

OR, if you just need the length:

int max = strings.stream().map(String::length).max(Integer::compareTo).get();

Or, if you prefer a one-liner, it's:

String longest = Arrays.asList(animals)
     .strings.stream().max(Comparator.comparingInt(String::length)).get();
=AND= 
int max = Arrays.asList(animals)
           .stream().map(String::length).max(Integer::compareTo).get();

Well, okay.. it's actually two-liner :-) Enjoy!

UPDATE:

Instead of Arrays.asList(animals).strings.stream() one could use directly Stream.of(animals)

Upvotes: 24

Greg Wojnowski
Greg Wojnowski

Reputation: 1

public class Main {

    public static void main(String[] args) {
        String [] names = {"Greg", "Aleksandra", "Martha", "Oliwka"};

        String wynik = findLongestName(names);
        System.out.println( wynik);
    }

    public static String findLongestName(String [] names){
        int size = names.length;
        String longestName = names[0];

        for(int i = 0; i <= 3; i++){
            if(names[i].length() > longestName.length()){
            longestName = names[i];
        }}

        return longestName;
    }
}

Upvotes: -3

Kashif Rizvee
Kashif Rizvee

Reputation: 1

public class LongestWord {
    public static void main(String []args)
    {
        System.out.println("Please enter the string for finding longest word");
        Scanner sc1 = new Scanner(System.in);
        String str = sc1.nextLine(), x=null;
        String str2[] = str.split(" ");

        x=str2[0];
        int i =0,j = 0;
        for( i = 0; i < str2.length; i = j)
        {
            for( j =i+1; j < str2.length; j++)
            {
                if(x.length() < str2[j].length())
                {
                    x = str2[j];
                    break;
                }
            }
        }
        System.out.println("the longest string is: " + x + " and it's length is: " + x.length());

    }
}

Upvotes: -2

punam kumari
punam kumari

Reputation: 1

I think there should not be array.length(); otherwise you'll be getting ArrayIndexOutOfBoundException because we cant use length() for array of string, instead we can use for particular string length.

Upvotes: -2

kidnan1991
kidnan1991

Reputation: 366

Here. 1. You use j<= animalNames.length;?

  1. You compare animalNames[j + 1]? -> error index out of array

  2. and you return in the first if condition return (animalNames[j]); -> wrong value

Ok, let me make clear. You find the longest string in an array. You loop over the array then you compare 2 near elements, and then return the bigger one. With your code, it will return the rabbit. Right?

May be you confuse about the process flow. There is a simple way.

  1. You assign a variable for the length of the first array element: elementLength = array[0].length; and a value to keep track of the index
  2. You loop over the array You check every element with this variable, if bigger then re-assign the element value and update the index.
  3. End of the loop. you have the biggest length and the index

Code:

int index = 0; 
int elementLength = array[0].length();
for(int i=1; i< array.length(); i++) {
    if(array[i].length() > elementLength) {
        index = i; elementLength = array[i].length();
    }
}
return array[index];

that is it.

Upvotes: 9

Related Questions