开发者

unble to replace string

开发者 https://www.devze.com 2022-12-19 05:03 出处:网络
This is my replace methodin java but unble to replace for following. It replace only one \\ Please help. If any body have any different method for replace?

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)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号