查找字符串数组中最长的字符串 [英] Finding the longest string in an array of Strings
问题描述
这个问题是我试图这样做,但我检查字符串长度的方法不起作用;我该怎么办才能修好它?
The problem with this is that i tried to do it but my method to check the length of the string is not working; what can I do to fix it?
public static void main(String[] args) {
String[] animalNames = {"cat", "rabbit", "horse", "goat", "rooster", "ooooooooooooooo"};
String a= getLongestString(animalNames);
System.out.println(a);
}
public static String getLongestString(String []animalNames) {
// String animalNames[] = {"cat","chicken","horse","ooooooooo" };
int j = 0;
for (j = 0; j <= animalNames.length; j++) {
if (animalNames[j].length() > animalNames[j + 1].length()) {
return (animalNames[j]);
}
}
return null;
}
}
推荐答案
下面。
1.您使用 j< = animalNames.length;
?
-
你比较
animalNames [j + 1]
? - >错误索引超出数组
You compare
animalNames[j + 1]
? -> error index out of array
并在第一个条件返回时返回(animalNames [j]);
- >错误值
and you return in the first if condition return (animalNames[j]);
-> wrong value
好的,让我说清楚。
您可以在数组中找到最长的字符串。循环遍历数组,然后比较2个近元素,然后返回更大的元素。
使用您的代码,它将返回兔子。对吗?
Ok, let me make clear. You find the longest string in an array. You loop over the array then you compare 2 near elements, and then return the bigger one. With your code, it will return the rabbit. Right?
您可能会对流程流程感到困惑。
有一种简单的方法。
May be you confuse about the process flow. There is a simple way.
- 为第一个数组元素的长度分配一个变量:elementLength = array [0 ]。长度;跟踪索引的值
- 循环遍历数组
使用此变量检查每个元素,如果更大则重新分配元素值并更新索引。 - 循环结束。你有最大的长度和指数
代码:
int index = 0;
int elementLength = array[0].length();
for(int i=1; i< array.length(); i++) {
if(array[i].length() > elementLength) {
index = i; elementLength = array[i].length();
}
}
return array[index];
就是这样。
这篇关于查找字符串数组中最长的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!