gpt4 book ai didi

java - 替换字符串中的字符序列不起作用

转载 作者:行者123 更新时间:2023-12-01 17:22:17 24 4
gpt4 key购买 nike

我正在将数据从 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. >

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

最佳答案

您可能的意思是:

a = a.replace(tmp, tmpWithHttp);

而不是:

a = a.replace(a, tmpWithHttp);

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

关于java - 替换字符串中的字符序列不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17766082/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com