# 找最长最短字符串

2019-11-11  22:18:09

```private static String findMin(String[] arr) {
String str4 = arr[0];
//String str5 = arr[arr.length-1];
int min = str4.length();
for (int i = 1; i < arr.length; i++) {
if (arr[i].length() < min) {
min = arr[i].length();
str4 = arr[i];
for (int j = i+1; j < arr.length; j++) {
if (arr[j].length() == arr[i].length()) {
String str5= arr[j];
str4=str4+" "+str5;
}
}
}
}
return str4+" ";
}```

```        Scanner s = new Scanner(System.in);
System.out.println("请输入n个字符串");
int n = s.nextInt();
String[] arr = new String[n];
s.nextLine();
System.out.println("请输入字符串");
for (int i = 0; i < n; i++) {
arr[i] = s.nextLine();
}```

```import java.util.Scanner;

//输入n行字符串，找出最长最短字符串（若有个数相同的，打印两个）
public class FindString {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("请输入n个字符串");
int n = s.nextInt();
String[] arr = new String[n];
s.nextLine();
System.out.println("请输入字符串");
for (int i = 0; i < n; i++) {
arr[i] = s.nextLine();
}
String max = findMax(arr);
System.out.println("最大的字符串：" + max.toString());//String已经重写了toString方法，所以会打印出字符串
String min = findMin(arr);
System.out.println("最小的字符串:" + min.toString());
}

private static String findMin(String[] arr) {
String str4 = arr[0];
//String str5 = arr[arr.length-1];
int min = str4.length();
for (int i = 1; i < arr.length; i++) {
if (arr[i].length() < min) {
min = arr[i].length();
str4 = arr[i];
for (int j = i+1; j < arr.length; j++) {
if (arr[j].length() == arr[i].length()) {
String str5= arr[j];
str4=str4+" "+str5;
}
}
}
}
return str4+" ";
}
private static String findMax(String[] arr) {
String str = arr[0];  //将数组的0号位定义为str长度最长的字符串，依次比较
//String str6 = arr[arr.length - 1];
//String[] strr = new String[arr.length];
int max = str.length();
for (int i = 1; i < arr.length; i++) {
if (arr[i].length() > max) {   //如果某个字符串的长度比它大
max = arr[i].length(); //将该字符串的长度更新为最大的
str = arr[i]; //并将该字符串赋给str
for (int j = i+1; j < arr.length; j++) { //如果有与这个字符串相同长度的
if (arr[j].length() == arr[i].length()) {
String str6 = arr[j];  //将这个字符串给新的str6,然后一起打印出来
str=str+"  "+str6;
}
}
}
}
return str + " ";
}

}```

(0)
(0)