如何用星号替换文本中的特定单词" *"等于单词的长度?

时间:2017-06-11 07:50:14

标签: java string

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

这是输入:

  

Linux,Windows

     

它不是Linux,它是GNU / Linux。 Linux只是内核,而GNU则增加了功能。因此,我们通过调用操作系统GNU / Linux来支持它们!此致,Windows客户端

这应该是输出:

  

它不是*****,它是GNU / *****。 *****仅仅是内核,而GNU则添加了功能。所以我们通过调用操作系统GNU / *****来归功于他们!真诚的,一个*******客户

这是我的代码:

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);

4 个答案:

答案 0 :(得分:2)

你可以这样做。这可以更有效地实现,但它足以完成您的任务。它基本上寻找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 / *****来归功于他们!真诚的,一个*******客户

答案 1 :(得分:0)

首先,您不需要使用while循环。 replace会自动替换每次事件。

其次,您可以使用StringBuilder构建一个具有特定数量的特定字符的新字符串:

StringBuilder sb = new StringBuilder();
for (int i = 0 ; i < someNumber ; i++) {
    sb.append("*");
}

我认为这就是你需要自己解决的问题。祝你好运!

答案 2 :(得分:0)

您可以使用String.format来解决您的问题,这是一个示例:

String[] words = {"Linux", "Windows"};//create an array for your word
for(String word : words){//loop throw this array
   str = str.replace(word, String.format("%0" + word.length() + "d", 0).replace("0", "*"));
}
System.out.println(str);

String.format("%0" + word.length() + "d", 0).replace("0", "*")会创建一个*长度为word.length的字符串,因此如果该字词为Linux,则会创建长度为*的字符串***** { {1}},等等......

<强>输出

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

答案 3 :(得分:0)

您可以通过在每个单词中使用*替换任何字符来创建替换字词:

for (String word : words)
{
  String replacement = word.replaceAll(".", "*");
  text = text.replaceAll(word, replacement);
}

word.replaceAll(".", "*")将使用*

替换单词中的任何字符