Java 找出长度最短字符串
时间: 2023-08-28 08:07:02 浏览: 120
要在 Java 中找出长度最短的字符串,你可以使用一个循环遍历字符串数组,并使用一个变量来记录当前最短字符串的索引。首先,假设数组中的第一个字符串是最短的,然后逐个比较数组中的其他字符串与当前最短字符串的长度,如果找到了更短的字符串,就更新最小长度和最小索引。
以下是一个示例代码:
```java
public class ShortestString {
public static void main(String[] args) {
String[] strings = {"apple", "banana", "cat", "dog", "elephant"};
int shortestIndex = 0;
int shortestLength = strings[0].length();
for (int i = 1; i < strings.length; i++) {
if (strings[i].length() < shortestLength) {
shortestLength = strings[i].length();
shortestIndex = i;
}
}
String shortestString = strings[shortestIndex];
System.out.println("The shortest string is: " + shortestString);
}
}
```
在上面的示例中,我们使用 `strings` 数组存储了一些字符串。通过遍历数组,我们找到了长度最短的字符串,并将其打印出来。运行代码后,输出结果应为:
```
The shortest string is: cat
```
这是根据给定的字符串数组找到了长度最短的字符串 "cat"。你可以根据自己的需求修改代码和输入的字符串数组。