
在处理文本或任何数据集合时,开发者常遇到的一个挑战是如何在循环迭代过程中,根据累积的结果或最终状态进行统一的输出。原始代码尝试在检测到重复词时立即打印提示信息,这导致了两个主要问题:
核心需求是:程序需要先完整地分析整个句子,识别所有连续重复的词,构建一个修正后的句子,然后根据原始句子与修正后句子的对比结果,一次性地输出带有特定格式的提示信息。
解决上述问题的关键在于将“处理逻辑”与“输出逻辑”进行分离。我们不应在处理数据的循环中直接进行最终的输出,而是应该:
这种模式确保了输出的准确性和清晰性,避免了在中间步骤产生不必要的干扰。
StringBuilder是Java中用于构建和修改字符串的推荐类,尤其在需要进行大量字符串拼接操作时,其性能远优于直接使用String的+运算符。
立即学习“Java免费学习笔记(深入)”;
以下是一个实现了上述逻辑的Java类:
import java.util.Objects; // For Objects.equals() which handles nulls gracefully
public class SentenceProcessor {
private String originalSentence;
public SentenceProcessor(String sentence) {
// 对输入句子进行非空检查和trim处理,提高健壮性
this.originalSentence = Objects.requireNonNull(sentence, "Sentence cannot be null").trim();
}
/**
* 处理句子,移除连续重复的单词,并按照指定格式输出结果。
* @return 修正后的句子字符串。
*/
public String processAndOutput() {
// 如果原始句子为空,直接返回空字符串并输出无重复信息
if (originalSentence.isEmpty()) {
System.out.println("There are no wrong repetitions");
return "";
}
// 将句子拆分为单词数组
// 使用正则表达式 "\s+" 可以处理多个连续空格的情况
String[] words = originalSentence.split("\s+");
StringBuilder correctedSentenceBuilder = new StringBuilder();
boolean repetitionsFound = false; // 标志位,用于记录是否发现连续重复词
// 遍历单词数组
for (int i = 0; i < words.length; i++) {
String currentWord = words[i];
// 判断是否为最后一个单词,或当前词与下一个词不连续重复
// 如果是最后一个词,或者当前词与下一个词不相等,则当前词是有效的
if (i == words.length - 1 || !currentWord.equalsIgnoreCase(words[i + 1])) {
correctedSentenceBuilder.append(currentWord);
// 如果不是最后一个有效词,则在其后添加空格
if (i < words.length - 1) {
// 检查下一个词是否会被跳过,如果下一个词会被跳过,则不加空格
// 否则,正常添加空格
if (i + 1 < words.length && currentWord.equalsIgnoreCase(words[i + 1])) {
// 如果下一个词是重复的,并且会被跳过,这里不加空格,因为我们i会跳过它
// 但为了避免在builder末尾留下多余空格,统一在最后trim
} else {
correctedSentenceBuilder.append(" ");
}
}
} else {
// 发现连续重复词:当前词与下一个词相同
repetitionsFound = true; // 设置标志位
i++; // 跳过下一个重复的词
}
}
// 将StringBuilder转换为最终的修正句子,并去除可能存在的末尾空格
String correctedSentence = correctedSentenceBuilder.toString().trim();
// 根据repetitionsFound标志位决定输出信息
if (repetitionsFound) {
System.out.println("The sentence includes wrong repetitions.");
System.out.println("The sentence should be: " + correctedSentence);
} else {
System.out.println("There are no wrong repetitions");
}
return correctedSentence; // 返回修正后的句子
}
// 示例用法
public static void main(String[] args) {
System.out.println("--- Test Case 1 ---");
SentenceProcessor processor1 = new SentenceProcessor("The operator did not not skip his meal");
processor1.processAndOutput();
// Expected Output:
// The sentence includes wrong repetitions.
// The sentence should be: The operator did not skip his meal
System.out.println("
--- Test Case 2 ---");
SentenceProcessor processor2 = new SentenceProcessor("Happy people live longer");
processor2.processAndOutput();
// Expected Output:
// There are no wrong repetitions
System.out.println("
--- Test Case 3 ---");
SentenceProcessor processor3 = new SentenceProcessor("This is an invalid invalid sentence that that needs corrected");
processor3.processAndOutput();
// Expected Output:
// The sentence includes wrong repetitions.
// The sentence should be: This is an invalid sentence that needs corrected
System.out.println("
--- Test Case 4 (Empty/Single word) ---");
SentenceProcessor processor4 = new SentenceProcessor("");
processor4.processAndOutput(); // Handles empty string
SentenceProcessor processor5 = new SentenceProcessor("Hello");
processor5.processAndOutput(); // Handles single word
System.out.println("
--- Test Case 5 (Case Insensitive) ---");
SentenceProcessor processor6 = new SentenceProcessor("Hello hello World");
processor6.processAndOutput(); // Handles case-insensitive check
}
}除了StringBuilder,我们也可以使用ArrayList<String>来存储非重复的单词,最后再将列表中的单词拼接成一个字符串。
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class SentenceProcessorWithList {
private String originalSentence;
public SentenceProcessorWithList(String sentence) {
this.originalSentence = Objects.requireNonNull(sentence, "Sentence cannot be null").trim();
}
public String processAndOutput() {
if (originalSentence.isEmpty()) {
System.out.println("There are no wrong repetitions");
return "";
}
String[] words = originalSentence.split("\s+");
List<String> validWords = new ArrayList<>(); // 使用ArrayList存储有效单词
boolean repetitionsFound = false;
for (int i = 0; i < words.length; i++) {
String currentWord = words[i];
// 同样判断是否为最后一个单词,或当前词与下一个词不连续重复
if (i == words.length - 1 || !currentWord.equalsIgnoreCase(words[i + 1])) {
validWords.add(currentWord); // 添加到列表中
} else {
repetitionsFound = true;
i++; // 跳过下一个重复的词
}
}
// 使用String.join()将列表中的单词拼接成一个字符串
String correctedSentence = String.join(" ", validWords);
if (repetitionsFound) {
System.out.println("The sentence includes wrong repetitions.");
System.out.println("The sentence should be: " + correctedSentence);
} else {
System.out.println("There are no wrong repetitions");
}
return correctedSentence;
}
public static void main(String[] args) {
System.out.println("--- Test Case (ArrayList) ---");
SentenceProcessorWithList processor = new SentenceProcessorWithList("The operator did not not skip his meal");
processor.processAndOutput();
}
}两种方法都能有效解决问题,开发者可以根据个人偏好和具体场景选择。对于本例,两者都非常适用。
本教程详细探讨了在Java中处理文本连续重复词的问题,并提供了一种高效且结构清晰的解决方案。核心思想在于将数据处理过程中的中间结果累积起来,并通过一个状态标志来记录关键事件,最终在所有处理完成后进行一次性、格式化的输出。通过使用StringBuilder或ArrayList,我们能够有效地构建修正后的字符串,同时避免了在循环中直接打印导致的混乱。掌握这种“结果累积与状态管理”的模式,对于解决各类涉及循环处理和统一输出的编程问题都具有重要的指导意义。
以上就是Java中处理文本重复词:高效检测、移除与格式化输出教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号