user2094397
user2094397

Reputation:

Replace char sequence in a string not working

I am retreiving data from a URL into a String a, and passing this string as an argument to gson's fromJson method. Now I need to replace some of the substrings in string a.

    String url = "abc";
    String a = getDataFromURL(url); //this string contains all the data from the URL, and getDataFromURL is the method that reads the data from the URL.
    String tmp = "\"reservation\":\"www.\"";
    String tmpWithHttp = "\"reservation\":\"http://www.\"";

    if(a.contains(tmp))
    {
    a = a.replace(a, tmpWithHttp);
    }

All the data in the URL is JSON. The requirement I have here is, if the String a contains a substring - "reservation":"www., replace that with "reservation":"http://www.

The above code I have is not working. Could someone please help me here?

Upvotes: 0

Views: 281

Answers (2)

FThompson
FThompson

Reputation: 28687

In your question, you specify that you want to replace "reservation":"www.. However, in your code, you've added an extra escaped quote, causing the replacement to search for "reservation":"www.", which isn't present in the string.

Simply remove that last escaped quote:

String tmp = "\"reservation\":\"www.";

Upvotes: 2

Rohit Jain
Rohit Jain

Reputation: 213193

You probably mean:

a = a.replace(tmp, tmpWithHttp);

instead of:

a = a.replace(a, tmpWithHttp);

And you don't need to do a contains() check before replacing. String#replace method will replace only if the substring to replace is present. So, you can remove the surrounding if.

Upvotes: 3

Related Questions