Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/354.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 替换字符串中不起作用的字符序列_Java - Fatal编程技术网

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

Java 替换字符串中不起作用的字符序列,java,Java,我正在将数据从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. S

我正在将数据从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
方法将仅在存在要替换的子字符串时进行替换。因此,如果您的意思可能是:

a = a.replace(tmp, tmpWithHttp);
而不是:

a = a.replace(a, tmpWithHttp);

在更换之前,您无需执行
contains()
检查
String#replace
方法将仅在存在要替换的子字符串时进行替换。因此,如果在您的问题中指定要替换
“reservation”:“www.
。但是,在您的代码中,您添加了一个额外的转义引号,导致替换搜索字符串中不存在的
“reservation:”www.“

只需删除最后一个转义引号:

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

在您的问题中,您指定要替换
“预订”:“www.
。但是,在您的代码中,您添加了一个额外的转义引号,导致替换者搜索
“reservation”:“www.”
,该引号不在字符串中

只需删除最后一个转义引号:

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

是的,很抱歉。我没有按原样粘贴代码。在问题中修改了它;)是的,很抱歉。我没有按原样粘贴代码。在问题中修改了它;)除了Rohit Jain的回答之外,您的代码正在检查
“预订”:“www.”
,而不是
“预订”:“www.
(如您的问题所述)。这个微小的差异可能会导致它找不到替换字符串。@Vulcan:将其作为答案发布。我很确定这是这里的真正错误。@Vulcan-你是100%正确的。是的,将其作为答案发布,我将接受:)除了Rohit Jain的答案之外,你的代码正在检查
“保留”:“www.”
,而不是
”预订“:“www.
(如您的问题所述)。这个微小的差异可能会导致它找不到替换字符串。@Vulcan:将其作为答案发布。我很确定这才是真正的错误。@Vulcan-你是100%正确的。是的,把它作为答案贴出来,我会接受的:)