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

编程入门 行业动态 更新时间:2024-10-18 12:32:31
本文介绍了查找字符串数组中最长的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

这个问题是我试图这样做,但我检查字符串长度的方法不起作用;我该怎么办才能修好它?

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

    就是这样。

    更多推荐

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

    本文发布于:2023-11-30 09:30:55,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1649506.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:字符串   组中   最长

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!