How to sort String array by length of each string present in an array
public class SortStrings {
public static void main(String args[]) {
String strarr[] = { "twersaoo", "threee", "one", "asjhgiqwg", "ahma djh", "h", "ajsvd", "abnbavs", "nbvvd" };
String result[] = method(strarr);
for (int i = 0; i < result.length; i++) {
System.out.println(result[i]);
}
}
public static String[] method(String str[]) {
for (int i = 0; i < str.length; i++) {
for (int j = 0; j < str.length - 1; j++) {
if (str[j].length() > str[j + 1].length()) {
String temp = str[j];
str[j] = str[j + 1];
str[j + 1] = temp;
}
}
}
return str;
}
}
Comments
Post a Comment