我需要在某些字符串中用“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();
}