This is my replace method in java but unble to replace for following.
It replace only one \
Please help. If any body have any different method for replace?
I had tried java s开发者_C百科tandard API but that is not working can please try following senario --> System.out.println(replace("this%s is the problem" , "%" , "\%"));
public static String replace(String str, String sub, String rep) {
int s, p, q;
int slen = sub.length();
StringBuffer sb = new StringBuffer();
s = 0;
p = str.indexOf(sub);
q = p + slen;
while (p != -1) {
sb.append(str.substring(s, p));
sb.append(rep);
s = q;
p = str.indexOf(sub, s);
if (p != -1) {
q = p + slen;
}
}
sb.append(str.substring(s));
return sb.toString();
}
You can use the replaceAll method. You just need to be careful escaping the \ and % (although I don't fully understand why you need four '\'s)!
String myString = "this%s is the problem";
myString = myString.replaceAll("%","\\\\%);
Escaping escape signs is a bit tedious in Java, but this should do what you want (if you want \\%
):
System.out.println("this%s is the problem".replace("%" , "\\\\%"));
If you want \%
it's this:
System.out.println("this%s is the problem".replace("%" , "\\%"));
Also note that this won't work properly with replaceAll
, which takes regexes, other than replace
.
There is a replaceAll() method
Why don't you use org.apache.commons.lang.StringUtils#replace(String, String, String)
精彩评论