我需要在某些字符串中用“chr(35)”替换所有“\ n#”或“\ n \ r#”“,那么考虑到性能问题,最好的方法是什么呢?
我试过这个,但我认为它不够好!!!
public String encodeHash(String data){
StringBuffer result = new StringBuffer();
int numberOfReplacedChars = 0;
String hashPattern1 = "\n#" ;
String hashPattern2 = "\n\r#" ;
int index = data.indexOf(hashPattern1);
if(index != -1 ){
numberOfReplacedChars = hashPattern1.length();
}else{
index = data.indexOf(hashPattern2);
if(index != -1){
numberOfReplacedChars = hashPattern2.length() ;
}else{
return data;
}
}
result.append(data.substring(0,index + (numberOfReplacedChars - 1)));
result.append("chr(35)");
// method call itself (recursive)
result.append(encodeHash(data.substring(index + numberOfReplacedChars)));
return result.toString();
}
答案 0 :(得分:2)
你可以尝试
str = str.replaceAll("\n\r?#", "chr(35)");
如果您要进行大量此操作,请使用Pattern
预编译正则表达式。
很难说这是否会比两个文字替换效果更好,所以如果真的是你的瓶颈,那么你应该为两个变量加上一些样本字符串。在大多数情况下,性能差异可以完全忽略不计。这是另一种选择:
str = str.replace("\n#", "chr(35)").replace("\n\r#", "chr(35)");
答案 1 :(得分:0)
@arshajii答案是对的。但是你可以尝试的另一种方法是扫描字符串中的每个字符串,然后执行StringBuilder#append。