java字符串,获取最长的一个单词,如有多个相同长度的单词返回第一个单词

假如输入:“hello china”则返回 hello
2025-05-11 19:32:54
推荐回答(1个)
回答1:

public static String test(){
String str = "hello wordss yes i do go houses";
String[] words = str.split(" ");
List list1 = new ArrayList();
List list2 = new ArrayList();
for(String word : words){
list1.add(word);
list2.add(word.length());
}
int maxLength = 0;
String maxStr = "";
for(int i=0;i if(maxLength maxLength = list2.get(i);
maxStr = list1.get(i);
}
}
System.out.println("第一个最长的单词:"+maxStr);
return maxStr;
}