输入n个字符串按首字母排序字符串
时间: 2024-06-13 12:09:23 浏览: 85
以下是Java实现输入n个字符串按首字母排序字符串的代码示例:
```java
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
public class SortStrings {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入字符串个数:");
int n = scanner.nextInt();
String[] strings = new String[n];
System.out.println("请输入" + n + "个字符串:");
for (int i = 0; i < n; i++) {
strings[i] = scanner.next();
}
Arrays.sort(strings, new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
return s1.charAt(0) - s2.charAt(0);
}
});
System.out.println("按首字母排序后的字符串为:");
for (String s : strings) {
System.out.print(s + " ");
}
}
}
```
运行示例:
```
请输入字符串个数:5
请输入5个字符串:
apple banana cat dog egg
按首字母排序后的字符串为:
apple banana cat dog egg
```
阅读全文