StringUtils - 在同一行替换不同的单词

时间:2015-04-27 14:39:04

标签: java apache-stringutils

我读到使用String.replaceAll非常慢。这就是我以旧方式做的事情:

String settence = "Java /*with*/ lambda /*expressions*/";
String replaceSettence = settence.replaceAll(Pattern.quote("/*with*/"), "is").replaceAll(Pattern.quote("/*expressions*/"), "future");

System.out.println(replaceSettence);

如何在一行中使用StringUtils执行此操作?

编辑:

感谢您的快速解答。

我使用Steph提供的代码。我的结论是,replaceAll必须比StringUtils更快:

  Long startTime = System.currentTimeMillis();
        String settence = "Java /*with*/ lambda /*expressions*/";
        String replaceSettence = settence.replaceAll(Pattern.quote("/*with*/"), "is").replaceAll(Pattern.quote("/*expressions*/"), "future");

        System.out.println(replaceSettence + " " + (System.currentTimeMillis() - startTime));

        String settenceStringUtils = "Java /*with*/ lambda /*expressions*/";
        String replaceStringUtils = StringUtils.replaceEach(settence, new String[]{"/*with*/", "/*expressions*/"}, new String[]{"is", "future"});
        System.out.println(replaceStringUtils + "StringUtils-> " + (System.currentTimeMillis() - startTime));

1 个答案:

答案 0 :(得分:3)

就像这样:

String settence = "Java /*with*/ lambda /*expressions*/";
String replaceSettence = StringUtils.replaceEach(settence, new String[]{"/*with*/", "/*expressions*/"}, new String[]{"is","future"});
System.out.println(replaceSettence);