gpt4 book ai didi

Java ReplaceAll vs For循环,其中包含替换

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:45:41 25 4
gpt4 key购买 nike

我有一个包含一些数据的字符串,我需要从中删除一些特殊字符并标记数据。

为了获得更好的性能,应首选以下两种方法中的哪一种:

String data = "Random data (For performance) Waiting for reply?"
data=data.replaceAll("?", "");
data=data.replaceAll(".", "");
data=data.replaceAll(",", "");
data=data.replaceAll("(", "");
data=data.replaceAll(")", "");

String[] tokens = data.split("\\s+");
for(int j = 0; j < tokens.length; j++){
//Logic on tokens
}

String data = "Random data (For performance) Waiting for reply?"

String[] tokens = data.split("\\s+");
for(int j = 0; j < tokens.length; j++){
tokens[j]=tokens[j].replace("?", "");
tokens[j]=tokens[j].replace(".", "");
tokens[j]=tokens[j].replace(",", "");
tokens[j]=tokens[j].replace("(", "");
tokens[j]=tokens[j].replace(")", "");

//Logic on each token
}

或者还有其他方法可以提高性能吗?(非常感谢关于相同的一些统计数据)

上面提供的 For 循环将用于对每个标记执行其他逻辑。
是对整个内容施加的替换方法更快,还是对 for 循环中的每个标记替换(无论替换如何执行)更快?

即Replace once and per other operations or replace step by step by replace for each token 然后执行所需的操作。

提前致谢

最佳答案

只需 replace 就足够了,没有任何循环。

replaceAll 在后台使用正则表达式引擎,但性能开销要大得多。

似乎对这个“全部”后缀有一个普遍的误解。

参见 Difference between String replace() and replaceAll() .

更新

发现了与这个非常相似的问题:

Removing certain characters from a string

关于Java ReplaceAll vs For循环,其中包含替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27017017/

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