Catfish
Catfish

Reputation: 19294

Trying to replace a substring of a string with another substring

I'm trying to take this string

where lowercase(pdd.last_name) like 'albert%' 

and replace "pdd" with "p" using this function

sb.replace(queryAdd.indexOf("pdd"), (queryAdd.indexOf("pdd") + 3), "p");

where sb is a StringBuffer, but it doesn't work and here's what it actually returns

where lowercase(pdpast_name) like 'albert%' 

Why does this not replace "pdd" with "p"?

Upvotes: 0

Views: 2896

Answers (3)

Chandra Sekhar
Chandra Sekhar

Reputation: 19502

StringBuffer s = new StringBuffer("where lowercase(pdd.last_name) like 'albert%'");
    s.replace(s.indexOf("pdd"),(s.indexOf("pdd")+3), "p");
    System.out.println(s);

I think your sb and queryAdd have different data.

Upvotes: 2

Shashank Kadne
Shashank Kadne

Reputation: 8101

It worked in my case. Have a look at my code (I am assuming this is what you are trying to do)....

StringBuffer sb = new StringBuffer("where lowercase(pdd.last_name) like 'albert%'");
        String queryAdd="where lowercase(pdd.last_name) like 'albert%'";
        sb.replace(queryAdd.indexOf("pdd"), (queryAdd.indexOf("pdd") + 3), "p");
        System.out.println(sb);

Output: where lowercase(p.last_name) like 'albert%'

Upvotes: 1

juergen d
juergen d

Reputation: 204766

Try this

String str = "where lowercase(pdd.last_name) like 'albert%'";
str = str.replaceFirst("pdd", "p");

Upvotes: 1

Related Questions