在第一个输入行上,我有应该替换的单词。第二个输入行用于文本。
这是输入:
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/