gpt4 book ai didi

java - 如何找到字符串中最长的单词?

转载 作者:行者123 更新时间:2023-12-01 07:44:01 25 4
gpt4 key购买 nike

我想找到给定字符串最长的单词

以下代码检查最长的单词,但我希望所有其他单词也具有相同的长度

try (BufferedReader fileInputReader = new BufferedReader(new FileReader(filePath))){
String line = fileInputReader.readLine();

line = line.replaceAll("[^äÄöÖüÜßa-zA-Z ]", "");
String[] sentence = line.split(" ");
String longestWord = "";

for (int i = 0; i < sentence.length; i++) {
if (sentence[i].length() > longestWord.length()) {
longestWord = sentence[i];
}
}

System.out.println(longestWord);
}

最佳答案

然后您必须使用这些最长单词集合,例如

  ArrayList<String> longestWords = new ArrayList<String>();
int longestWordLength = 0;

for (int i = 0; i < sentence.length; i++) {
if (sentence[i].length() > longestWordLength) { // longer
longestWordLength = sentence[i].length();
longestWords.clear();
longestWords.add(sentence[i]);
}
else if (sentence[i].length() == longestWordLength) { // same length
longestWords.add(sentence[i]);
}
}

for (int i = 0; i < longestWords.size(); ++i)
System.out.println(longestWords.get(i));

关于java - 如何找到字符串中最长的单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58502164/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com