我想从一个字符中删除一部分字符串,即:
源字符串:
manchester united (with nice players)
Run Code Online (Sandbox Code Playgroud)
目标字符串:
manchester united
Run Code Online (Sandbox Code Playgroud) 我必须编写某种解析器来获取String并用其他字符替换某些字符集.代码如下所示:
noHTMLString = noHTMLString.replaceAll("</p>", "\n");
noHTMLString = noHTMLString.replaceAll("<br/>", "\n\n");
noHTMLString = noHTMLString.replaceAll("<br />", "\n\n");
//here goes A LOT of lines like these ones
Run Code Online (Sandbox Code Playgroud)
该函数非常长并且执行许多字符串替换.这里的问题是它需要花费很多时间,因为它被称为很多次的方法,从而降低了应用程序的性能.
我已经阅读了一些关于使用StringBuilder作为替代方案的一些线程,但它缺少ReplaceAll方法,并且正如此处所述,string.replaceAll()性能是否受到字符串不变性的影响?String类中的replaceAll方法适用于
Match Pattern&Matcher和Matcher.replaceAll()使用StringBuilder存储最终返回的值,因此我不知道切换到StringBuilder是否会真正减少执行替换的时间.
您是否知道以快速方式快速完成大量String替换?你对这个问题有什么建议吗?
谢谢.
编辑:我必须创建一个报告,其中包含一些带有html文本的字段.对于每一行,我正在调用替换这些字符串中的所有html标记和特殊字符的方法.使用完整报告,解析所有文本需要3分钟以上.问题是我必须经常调用该方法
我认为String.indexOf(char)比String.indexOf(String)使用单个字符和单个字符串(例如,'x'和"x")快一点
为了确保我的猜测,我编写了简单的测试代码,如下所示.
public static void main(String[] args) {
IndexOfTest test = new IndexOfTest(Integer.parseInt(args[0]));
test.run();
}
public IndexOfTest(int loop) {
this.loop = loop;
}
public void run() {
long start, end;
start = System.currentTimeMillis();
for(int i = 0 ; i < loop ; i++) {
alphabet.indexOf("x");
}
end = System.currentTimeMillis();
System.out.println("indexOf(String) : " + (end - start) + "ms");
start = System.currentTimeMillis();
for(int i = 0 ; i < loop ; i++) {
alphabet.indexOf('x');
}
end = …Run Code Online (Sandbox Code Playgroud) 是否有任何理由要使用String.replaceAll(String,String)而不是StringUtils.replace()全部使用?
假设两个库都可用,并且我们没有传递正则表达式。
从关于这一主题的几个以前的职位,我看到有多个测试和基准指着那String.replace是缓慢的,但我不记得任何人解释是否有使用的情况下,String.replaceAll在StringUtils.replace
我注意到String.replace(CharSequence, CharSequence)java 12 和 13 之间的行为有所不同。
java 12 及更早版本:
System.out.println("String"=="String".replace("g","g")); //false
Run Code Online (Sandbox Code Playgroud)
Java 13 及更高版本:
System.out.println("String"=="String".replace("g","g")); //true
Run Code Online (Sandbox Code Playgroud)
发现这可能是由于:
针对常见情况优化 String.replace(CharSequence, CharSequence)
这是意外行为吗?
是的,我知道 equals 方法。