【问题标题】:Replacing Strings Java替换字符串 Java
【发布时间】:2015-05-02 01:10:42
【问题描述】:

我有这个功能来检查某些单词是否出现在特定的行中,然后用给定的字符将它们包围。

上面的代码就像一个魅力,但是由于字符串数组“words”中的单词总是小写的,所以单词也将是小写的。我该如何解决这个问题?

输入:

BufferedReader in = "Hello, my name is John:";
char c = '*';
String [] words = {"hello","john"}; 

想要的输出:

BufferedWriter out = "*Hello*, my name is *John*:";

实际输出:

BufferedWriter out = "*hello*, my name is *john*";

代码:

public void replaceString(BufferedReader in, BufferedWriter out, char c, String[] words){

String line_in = in.readLine();

    while (line_in != null) {
        for (int j = 0; j < words.length; j++) {

            line_in = line_in.replaceAll("(?i)" + words[j], bold + words[j]
                    + bold);

        }

        out.write(line_in);
        out.newLine();
        line_in = in.readLine();

    }
}

【问题讨论】:

    标签: java string replace buffer lowercase


    【解决方案1】:

    使用

    line_in.replaceAll("(?i)(" + words[j] + ")", bold + "$1" + bold);
    //                      \________________/           \/
    //                         capture word          reference it
    

    【讨论】:

      猜你喜欢
      • 2021-01-27
      • 1970-01-01
      • 1970-01-01
      • 2015-12-23
      • 1970-01-01
      • 1970-01-01
      • 2015-05-01
      • 2013-07-09
      • 2016-07-19
      相关资源
      最近更新 更多