java - 如何用星号替换文本中的特定单词“*"equal to the word' s 长度?

标签 java string

在第一个输入行上,我有应该替换的单词。第二个输入行用于文本。

这是输入:

Linux, Windows

It is not Linux, it is GNU/Linux. Linux is merely the kernel, while GNU adds the functionality. Therefore we owe it to them by calling the OS GNU/Linux! Sincerely, a Windows client

这应该是输出:

It is not *****, it is GNU/*****. ***** is merely the kernel, while GNU adds the functionality. Therefore we owe it to them by calling the OS GNU/*****! Sincerely, a ******* client

这是我的代码:

String[] words = br.readLine().split(", ");
String text = br.readLine();

for (String word : words) {
    while (text.contains(word)) {    
        text = text.replace(word, "*");// i can replace only the first character in the word with asterisks.
    }
}
System.out.println(text);

最佳答案

你可以做这样的事情。这可以更有效地实现,但它足以满足您的任务。它基本上查找 Windows 和 Linux 的出现,并用给定字长的适当数量的星号替换它们。

String wordLinux = "Linux";
String wordWindows = "Windows";
String s = "It is not Linux, it is GNU/Linux. Linux is merely the kernel, while GNU adds the functionality. Therefore we owe it to them by calling the OS GNU/Linux! Sincerely, a Windows client";

StringBuilder sbLinux = new StringBuilder();
for (int idx = 0; idx != wordLinux.length(); ++idx)
    sbLinux.append("*");
s = s.replaceAll(wordLinux, sbLinux.toString());    

StringBuilder sbWindows = new StringBuilder();
for (int idx = 0; idx != wordWindows.length(); ++idx)
    sbWindows.append("*");
s = s.replaceAll(wordWindows, sbWindows.toString());    

System.out.println(s);

程序的输出结果:

这不是 *****,而是 GNU/*****。 ***** 只是内核,而 GNU 添加了功能。因此,我们将操作系统称为 GNU/***** 来感谢他们!此致,******** 客户

关于java - 如何用星号替换文本中的特定单词“*"equal to the word' s 长度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44481557/

相关文章:

java - 使用 TrueZip 以独立于平台的方式读取 ZIP 文件

java - 带有泛型参数的主方法;为什么它起作用?

java 字符串连续比较

c# - 检查字符串哈希是否包含子字符串哈希

c# - 带字符串的选择排序

java - 在 Java 中使用套接字的 HTTP 1.1 持久连接

java - 传递参数的通用方法 - java.lang.ClassCastException : com. google.gson.internal.LinkedTreeMap

java - 从命令行运行,名称错误

java - 如何根据字符串的长度对 List<String> 进行排序并打印前 N 个元素

c++ - 从 boost::archive:binary_iarchive 反序列化 std::string 时分配错误异常