[英]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. 我将URL中的数据检索到String a中,并将此字符串作为参数传递给gson的fromJson方法。 Now I need to replace some of the substrings in string a.
现在,我需要替换字符串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. URL中的所有数据均为JSON。 The requirement I have here is, if the String a contains a substring -
"reservation":"www.
, replace that with "reservation":"http://www.
我在这里的要求是,如果字符串a包含一个子字符串-
"reservation":"www.
,则将其替换为"reservation":"http://www.
The above code I have is not working. 我上面的代码无法正常工作。 Could someone please help me here?
有人可以帮我吗?
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. 而且,您无需在替换之前进行
contains()
检查。 String#replace
method will replace only if the substring to replace is present. 仅当存在要替换的子字符串时,才会替换
String#replace
方法。 So, you can remove the surrounding if
. 所以,你可以删除周围
if
。
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. 在您的问题中,您指定要替换
"reservation":"www.
。但是,在代码中,您添加了一个额外的转义引号,导致替换内容搜索"reservation":"www."
,在字符串中不存在。
Simply remove that last escaped quote: 只需删除最后一个转义的报价:
String tmp = "\"reservation\":\"www.";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.