java - 如何找到字符串中最长的单词?
问题描述
我想在给定的String
.
以下代码检查最长的单词,但我也希望每个其他单词的长度都相同。
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);
}
解决方案
然后你必须使用这些的集合longestWords
,例如
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));
推荐阅读
- python - 编写一个循环以根据两个或多个列的值找出唯一的年份
- terraform-provider-gcp - GCE 在创建的指标之一不存在时发出警报(通过 terraform)
- android - Android 地图:如何使用 SVG 文件自定义标记图标?
- python - 使用 scikit-image 计算图像中特定区域的平均灰度值
- xamarin.forms - Xamarin 表单四舍五入 SearchHandler
- python - 在 Cloudformation 中使用时无法从 S3 下载引导文件
- autodesk-forge - 在 Forge 查看器中覆盖 dblclick 行为
- php - WooCommerce 块 - 将简短的产品描述添加到产品网格
- django - 如何使用 PageChooserBlocks 的 ListBlocks 对 StreamField 的 APIField 进行 JSON 序列化
- c# - ResolveUrl XSS 替代方案