输入n个字符串,将输入的字符串按字母顺序进行排序,如果第一个字母相同,则按照第二个字符开始按照字母顺序,生成java代码
时间: 2024-06-10 08:08:38 浏览: 127
public class StringSorting {
public static void main(String[] args) {
String[] strings = {"abc", "cba", "bcd", "bca"};
sortStrings(strings);
for (String s : strings) {
System.out.println(s);
}
}
public static void sortStrings(String[] strings) {
for (int i = 0; i < strings.length - 1; i++) {
for (int j = i + 1; j < strings.length; j++) {
if (compareStrings(strings[i], strings[j]) > 0) {
String temp = strings[i];
strings[i] = strings[j];
strings[j] = temp;
}
}
}
}
public static int compareStrings(String str1, String str2) {
int length = Math.min(str1.length(), str2.length());
for (int i = 0; i < length; i++) {
char c1 = str1.charAt(i);
char c2 = str2.charAt(i);
if (c1 != c2) {
return c1 - c2;
}
}
return str1.length() - str2.length();
}
}
相关问题:
1. 如何按照字符串长度进行排序?
2. 如何在降序中对字符串进行排序?
3. 如何在不区分大小写的情况下对字符串
阅读全文