Printing the Longest String in an Array
This code snippet will quite happily return the longest string in an array/
In this example it will return the string 'three'.
A brief explanation of the code basically the for loop and if statement check the length of C[1] which is the first string in the array and then increases the string number by one so C[2] and checks the string length again. It then records down which string has the longest length, and prints out the string when the for loop completes.
[java]
public class labarray {
public static void main( String args [] )
{
String C[] = {"one","two","three","four","five"};
String longeststring = null;
int length = 0;
for (int i=0; i<C.length; i++)
{
if (C.length()>length)
{
length = C.length();
longeststring = C;
}
}
System.out.println(longeststring);
}
}
[/java]
Java Applets Coming Soon!!! Funnsies!!
This code snippet will quite happily return the longest string in an array/
In this example it will return the string 'three'.
A brief explanation of the code basically the for loop and if statement check the length of C[1] which is the first string in the array and then increases the string number by one so C[2] and checks the string length again. It then records down which string has the longest length, and prints out the string when the for loop completes.
[java]
public class labarray {
public static void main( String args [] )
{
String C[] = {"one","two","three","four","five"};
String longeststring = null;
int length = 0;
for (int i=0; i<C.length; i++)
{
if (C.length()>length)
{
length = C.length();
longeststring = C;
}
}
System.out.println(longeststring);
}
}
[/java]
Java Applets Coming Soon!!! Funnsies!!