Java 查找字符串数组中最长的字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26725296/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 03:10:09  来源:igfitidea点击:

Finding the longest string in an array of Strings

java

提问by Dee

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;
    }

}

采纳答案by kidnan1991

Here. 1. You use j<= animalNames.length;?

这里。1. 你用j<= animalNames.length;?

  1. You compare animalNames[j + 1]? -> error index out of array

  2. and you return in the first if condition return (animalNames[j]);-> wrong value

  1. 你比较animalNames[j + 1]?-> 错误索引超出数组

  2. 并且您在第一个 if 条件中返回return (animalNames[j]);-> 错误值

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?

好吧,让我说清楚。您找到数组中最长的字符串。您遍历数组,然后比较 2 个附近的元素,然后返回较大的元素。使用您的代码,它将返回兔子。对?

May be you confuse about the process flow. There is a simple way.

您可能对流程感到困惑。有一个简单的方法。

  1. You assign a variable for the length of the first array element: elementLength = array[0].length; and a value to keep track of the index
  2. You loop over the array You check every element with this variable, if bigger then re-assign the element value and update the index.
  3. End of the loop. you have the biggest length and the index
  1. 您为第一个数组元素的长度分配一个变量: elementLength = array[0].length; 和跟踪索引的值
  2. 你遍历数组你用这个变量检查​​每个元素,如果更大,则重新分配元素值并更新索引。
  3. 循环结束。你有最大的长度和索引

Code:

代码:

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];

that is it.

这就对了。

回答by punam kumari

I think there should not be array.length();otherwise you'll be getting ArrayIndexOutOfBoundExceptionbecause we cant use length() for array of string, instead we can use for particular string length.

我认为不应该有array.length();否则你会得到,ArrayIndexOutOfBoundException因为我们不能使用 length() 字符串数组,而是我们可以使用特定的字符串长度。

回答by Kashif Rizvee

public class LongestWord {
    public static void main(String []args)
    {
        System.out.println("Please enter the string for finding longest word");
        Scanner sc1 = new Scanner(System.in);
        String str = sc1.nextLine(), x=null;
        String str2[] = str.split(" ");

        x=str2[0];
        int i =0,j = 0;
        for( i = 0; i < str2.length; i = j)
        {
            for( j =i+1; j < str2.length; j++)
            {
                if(x.length() < str2[j].length())
                {
                    x = str2[j];
                    break;
                }
            }
        }
        System.out.println("the longest string is: " + x + " and it's length is: " + x.length());

    }
}

回答by Greg Wojnowski

public class Main {

    public static void main(String[] args) {
        String [] names = {"Greg", "Aleksandra", "Martha", "Oliwka"};

        String wynik = findLongestName(names);
        System.out.println( wynik);
    }

    public static String findLongestName(String [] names){
        int size = names.length;
        String longestName = names[0];

        for(int i = 0; i <= 3; i++){
            if(names[i].length() > longestName.length()){
            longestName = names[i];
        }}

        return longestName;
    }
}

回答by Nestor Milyaev

It's real simple using java 8 (just check that your array is not empty first or process the .get()specially):

使用 java 8 非常简单(只需先检查您的数组是否为空或.get()专门处理):

List<String> strings = Arrays.asList(animals);    
int max = strings.stream().map(String::length).max(Integer::compareTo).get();

Or, if you prefer a one-liner, it's:

或者,如果您更喜欢单线,它是:

int max = Arrays.asList(animals)
    .stream().map(String::length).max(Integer::compareTo).get();

Well, okay.. it's actually two-liner :-) Enjoy!

好吧,好吧..它实际上是两行的 :-) 享受吧!