gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 22:20:32 25 4
gpt4 key购买 nike

我读到使用 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));

最佳答案

就像这样:

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

关于java - StringUtils - 替换同一行的不同单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29898799/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com