我有一个Java字符串作为服务器["This is my "json response", "jshj" "," "sdjfh,sfjg" ",""Abs, "jshj" ",""Abs, "jshj" ",""Abs, "jshj"",""Abs, "jshj" "].
的响应
我想在定界符“,”上将字符串拆分为5个子字符串,以便将结果存储到数组中。
预期输出为:
这是我的“ json响应”,“ jshj”,“ sdjfh,sfjg”,“ Abs”,“ jshj”,“ Abs, “ jshj”“ Abs,” jshj“” Abs,“ jshj”
以下是我的方法:
String arrayGenerated[] =result.replaceAll("[\\[\\]\"]", "").split(__________,5);
return arrayGenerated;
请提出我应该在拆分部分中提及的内容。
答案 0 :(得分:0)
在解析服务器响应之后,可以使用 String.split(“ regular expression”)方法来拆分响应。
String a = "[\"This is my \"json response\", \"jshj\" \",\" \"sdjfh,sfjg\" \",\"\"Abs, \"jshj\" \",\"\"Abs, \"jshj\" \",\"\"Abs, \"jshj\"\",\"\"Abs, \"jshj\" \"]";
String arr[] = a.split("\",\"");
答案 1 :(得分:0)
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Test1222 {
public static void main(String[]args)
{
String fileName = "C:\\\filepath";
List<String> list = null;
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
list = stream.collect(Collectors.toList());
} catch (IOException e) {
e.printStackTrace();
}
String str = list.get(0);
String str1 = str.replaceAll("\\[", "").replaceAll("\\]","");
String[] strArr = str1.split(",");
List<String> resultArr = Arrays.asList(strArr);
List<String> result = resultArr.stream().collect(Collectors.toList());
result.forEach(System.out::println);
}
}
答案 2 :(得分:0)
您可以传递服务器响应,然后按如下所示拆分响应,
String str = "[\"This is my \"json response\", \"jshj\" \",\" \"sdjfh,sfjg\" \",\"\"Abs, \"jshj\" \",\"\"Abs, \"jshj\" \",\"\"Abs, \"jshj\"\",\"\"Abs, \"jshj\" \"]";
str = str.replaceAll("\\[", "").replaceAll("\\]", ""); // To remove []
List<String> list = Arrays.asList(str.split(",")); // Simply separate words by comma to a list that you can iterate
for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) {
String next = iterator.next();
System.out.println(next);
}
如果您需要从服务器响应中删除双引号,则可以使用以下语句,
str.replaceAll("\"", "")
答案 3 :(得分:0)
您可以执行以下操作:
public class Main {
public static void main(String[] args) {
String resString = "[\"This is my \"json response\", \"jshj\" \",\" \"sdjfh,sfjg\" \",\"\"Abs, \"jshj\" \",\"\"Abs, \"jshj\" \",\"\"Abs, \"jshj\"\",\"\"Abs, \"jshj\" \"]";
String str = resString.replaceAll("\\[", "").replaceAll("\\]", ""); // Remove [ and ]
String substrs[] = str.split("\",\""); // Split at ","
for(int i=0;i<substrs.length;i++)
substrs[i]=substrs[i].trim(); // Trim each substring
int li=substrs.length-1; //Index of last substring in the array
substrs[li]=substrs[li].substring(0,substrs[li].lastIndexOf("\"")).trim(); // In the last String, remove extra " from the end
for(String substr:substrs)
System.out.println(substr);
}
}
输出:
"This is my "json response", "jshj"
"sdjfh,sfjg"
"Abs, "jshj"
"Abs, "jshj"
"Abs, "jshj"
"Abs, "jshj"