0

我正在从 URL 检索数据到字符串 a,并将该字符串作为参数传递给 gson 的 fromJson 方法。现在我需要替换字符串 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);
    }

URL 中的所有数据都是 JSON。我在这里的要求是,如果字符串 a 包含子字符串 - "reservation":"www.,请将其替换为"reservation":"http://www.

我上面的代码不起作用。有人可以在这里帮助我吗?

4

2 回答 2

3

你可能的意思是:

a = a.replace(tmp, tmpWithHttp);

代替:

a = a.replace(a, tmpWithHttp);

而且您无需contains()在更换前进行检查。String#replace仅当要替换的子字符串存在时,方法才会替换。因此,您可以删除周围的if.

于 2013-07-20T19:52:55.637 回答
2

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.";
于 2013-07-20T20:03:55.743 回答