[英]Replace Brackets on Array
I have an array like this: ["one", two"]
我有一个这样的数组: ["one", two"]
If I make array.toString().replace("[", "").replace("]", "").trim();
如果我制作array.toString().replace("[", "").replace("]", "").trim();
, I will have: "one, two"
,我会有: "one, two"
What I really want is "one", "two"
我真正想要的是"one", "two"
How can I do this?我怎样才能做到这一点?
EDIT:编辑:
This is a simple program to explain my question:这是一个简单的程序来解释我的问题:
ArrayList<String> array = new ArrayList<>();
array.add("one");
array.add("two");
String stringArray = array.toString().replace("[", "").replace("]", "");
Gson gson = new Gson();
String json = gson.toJson(stringArray);
System.out.println(json);
You can try with你可以试试
array.stream().map(s->"\""+s+"\"").collect(Collectors.joining(", "));
which will first surround each strings with quotes, then join them using ,
这将首先用引号将每个字符串括起来,然后使用,
For Java 7对于 Java 7
String delimiter = ", ";
StringBuilder sb = new StringBuilder();
if (!array.isEmpty()) {
sb.append('"').append(array.get(0)).append('"');
}
for (int i = 1; i < array.size(); i++) {
sb.append(delimiter).append('"').append(array.get(i)).append('"');
}
String result = sb.toString();
Well, just replace comma's with some extra "
's好吧,只需用一些额外的"
替换逗号
array.toString().replace("[", "").replace("]", "").trim().replace(", ", "\", \"")
(Not tested, but you get the idea) (未经测试,但你明白了)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.