Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/three.js/2.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 如何对字符串使用indexOf方法多次提取字符串?_Java_Indexof - Fatal编程技术网

Java 如何对字符串使用indexOf方法多次提取字符串?

Java 如何对字符串使用indexOf方法多次提取字符串?,java,indexof,Java,Indexof,我有3个不同的字符串,我试图使用indexOf和substring从每个字符串中提取特定的字符串。但是,我不想重复indexOf,因此可能会重复代码中的时间。有没有一种方法可以重用代码从给定的较大字符串中提取所需的字符串?任何帮助都会很好,非常感谢 String message1 = content1.substring(content1.indexOf(" \\\"message\\\": \\") + 1, content1.indexOf("\\\" }")).substring(15);

我有3个不同的字符串,我试图使用
indexOf
substring
从每个字符串中提取特定的字符串。但是,我不想重复
indexOf
,因此可能会重复代码中的时间。有没有一种方法可以重用代码从给定的较大字符串中提取所需的字符串?任何帮助都会很好,非常感谢

String message1 = content1.substring(content1.indexOf(" \\\"message\\\": \\") + 1, content1.indexOf("\\\" }")).substring(15);
String message2 = content2.substring(content2.indexOf(" \\\"message\\\": \\") + 1, content2.indexOf("\\\" }")).substring(15);
String message3 = content3.substring(content3.indexOf(" \\\"message\\\": \\") + 1, content3.indexOf("\\\" }")).substring(15);

如果您只想编写一个方法,其功能完全相同,请尝试:

public static String extractMessage(String content){
  return content.substring(content.indexOf(" \\\"message\\\": \\") + 1, content.indexOf("\\\" }")).substring(15);
}
然后这样称呼它:

String message1 = extractMessage(content1);
String message2 = extractMessage(content2);
String message3 = extractMessage(content3);

int
传递给
indexOf
作为第二个参数。
int
是搜索的起始索引。您不应该使用JSON解析器吗?您可以将
16
而不是
1
添加到起始索引中,以避免调用
子字符串两次。