How to find longest string?

How can I find the longest string in a string array?
[59 byte] By [bonoza] at [2007-10-2 18:17:00]
# 1

> How can I find the longest string in a string array?

By looping through the array and using the length() method of the String class.

Details:

http://java.sun.com/docs/books/tutorial/java/nutsandbolts/for.html

http://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.html

Please post these kind of questions int the New To Java-section of the forum:

http://forum.java.sun.com/forum.jspa?forumID=54

prometheuzza at 2007-7-13 19:37:14 > top of Java-index,Other Topics,Algorithms...
# 2

Say you had an array called stringy

String [ ] stringy;

int current = stringy[0].length();

int longest = 0;

for(int i=0;i<stringy.length;i++){

longest = Math.max(current, stringy[i])

}

for(int i=0;i<stringy.length;i++){

int l = stringy[i].length();

if(l == longest){

String longstring = stringy[i];

}

}

this will set "longest" to be the longest string then you need to loop through the array again and match this length with all the stringsn the array when they match you have found the longest string. Probably not the most elegant way of doing it but it should work.>

some1stolemyusernamea at 2007-7-13 19:37:14 > top of Java-index,Other Topics,Algorithms...
# 3
@some1stolemyusername: besides the fact your code will never compile, the OP's assignment has already been handed in. http://forum.java.sun.com/thread.jspa?threadID=729840 , reply #12.
prometheuzza at 2007-7-13 19:37:14 > top of Java-index,Other Topics,Algorithms...
# 4
dude, u are a genius..the code works ... thanks a lot!!!!
insomniuma at 2007-7-13 19:37:14 > top of Java-index,Other Topics,Algorithms...
# 5
> dude, u are a genius..> the code works ... thanks a lot!!!!Yey, at last we have a proof! 2nd Einstein was born!
maf69a at 2007-7-13 19:37:14 > top of Java-index,Other Topics,Algorithms...