
本教程详细介绍了如何在Java中计算一个字符串中唯一单词的数量,忽略重复项。我们将利用字符串分割功能将文本拆分为单词,并结合ArrayList来高效地存储和检查单词的唯一性,最终返回唯一单词的总数,整个过程避免使用高级集合类型如HashSet。
计算字符串中唯一单词数量的核心在于两点:
为了满足“只允许使用基础功能,不使用哈希集合等高级特性”的要求,我们可以采用String类的split()方法来分割字符串,并使用ArrayList来存储和检查单词的唯一性。
以下是实现唯一单词计数方法的具体步骤:
立即学习“Java免费学习笔记(深入)”;
下面是一个完整的Java方法实现,它接受一个字符串作为参数,并返回其中唯一单词的数量:
import java.util.ArrayList;
import java.util.List;
public class WordCounter {
/**
* 计算给定字符串中唯一单词的数量。
* 该方法通过将字符串按空格分割,并使用ArrayList来存储和检查单词的唯一性。
*
* @param s 待处理的输入字符串。
* @return 字符串中唯一单词的总数。
*/
public static int countUniqueWords(String s) {
// 如果字符串为空或只包含空白字符,则直接返回0
if (s == null || s.trim().isEmpty()) {
return 0;
}
// 1. 将字符串按空格分割成单词数组
// 注意:简单的split(" ")可能会保留标点符号,例如 "ago," 会被视为一个单词。
// 如果需要更严格的单词定义(例如,只包含字母),可能需要先去除标点符号或使用正则表达式。
String[] words = s.split(" ");
// 2. 创建一个列表来存储唯一单词
List<String> uniqueWords = new ArrayList<>();
// 3. 遍历单词数组,检查并添加唯一单词
for (String word : words) {
// 清理单词,例如去除首尾空格
String cleanedWord = word.trim();
// 忽略空字符串,这可能由多个空格或trim()操作产生
if (cleanedWord.isEmpty()) {
continue;
}
// 检查单词是否已存在于唯一单词列表中
// 此处是大小写敏感的,"Hello"和"hello"会被视为不同的单词。
if (!uniqueWords.contains(cleanedWord)) {
uniqueWords.add(cleanedWord);
}
}
// 4. 返回唯一单词的数量
return uniqueWords.size();
}
public static void main(String[] args) {
String input1 = "A long long time ago, I can still remember";
int uniqueCount1 = countUniqueWords(input1);
System.out.println("Input: "" + input1 + """);
System.out.println("Number of unique words: " + uniqueCount1); // 预期输出: 8 (A, long, time, ago,, I, can, still, remember)
String input2 = "Hello world hello java World";
int uniqueCount2 = countUniqueWords(input2);
System.out.println("Input: "" + input2 + """);
System.out.println("Number of unique words: " + uniqueCount2); // 预期输出: 5 (Hello, world, hello, java, World)
String input3 = " one two one ";
int uniqueCount3 = countUniqueWords(input3);
System.out.println("Input: "" + input3 + """);
System.out.println("Number of unique words: " + uniqueCount3); // 预期输出: 2 (one, two)
String input4 = "";
int uniqueCount4 = countUniqueWords(input4);
System.out.println("Input: "" + input4 + """);
System.out.println("Number of unique words: " + uniqueCount4); // 预期输出: 0
}
}运行示例代码的输出:
Input: "A long long time ago, I can still remember" Number of unique words: 8 Input: "Hello world hello java World" Number of unique words: 5 Input: " one two one " Number of unique words: 2 Input: "" Number of unique words: 0
通过本教程,我们学习了如何在Java中利用基础的字符串操作和ArrayList数据结构,实现一个计算字符串中唯一单词数量的方法。这个方法遵循了在不使用高级集合类(如HashSet)的前提下解决问题的要求。在实际应用中,根据对单词定义的严格程度和性能需求,可以进一步优化字符串预处理和去重机制。
以上就是Java教程:实现字符串中唯一单词的计数方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号