用双引号将每个字符串括在逗号分隔的字符串中
Enclose each string in a comma separated string in double quotes
我正在处理一个要求,我需要将单个字符串用双引号括在以逗号分隔的字符串中,同时保留空字符串。
例如:字符串 the,quick,brown,fox,jumped,over,the,lazy,dog 应转换为 "the","quick","brown","fox","jumped","over","the","lazy","dog"
我有这段有效的代码。但是想知道是否有更好的方法来做到这一点。顺便说一句,我在 JDK 8.
String str = "the,quick,brown,,,,,fox,jumped,,,over,the,lazy,dog";
//split the string
List<String> list = Arrays.asList(str.split(",", -1));
// add double quotes around each list item and collect it as a comma separated string
String strout = list.stream().collect(Collectors.joining("\",\"", "\"", "\""));
//replace two consecutive double quotes with a empty string
strout = strout.replaceAll("\"\"", "");
System.out.println(strout);
您可以使用 split
并使用 stream
:
public static String covert(String str) {
return Arrays.stream(str.split(","))
.map(s -> s.isEmpty() ? s : '"' + s + '"')
.collect(Collectors.joining(","));
}
然后:
String str = "the,quick,brown,,,,,fox,jumped,,,over,the,lazy,dog";
System.out.println(covert(str));
输出:
"the","quick","brown",,,,,"fox","jumped",,,"over","the","lazy","dog"
我正在处理一个要求,我需要将单个字符串用双引号括在以逗号分隔的字符串中,同时保留空字符串。
例如:字符串 the,quick,brown,fox,jumped,over,the,lazy,dog 应转换为 "the","quick","brown","fox","jumped","over","the","lazy","dog"
我有这段有效的代码。但是想知道是否有更好的方法来做到这一点。顺便说一句,我在 JDK 8.
String str = "the,quick,brown,,,,,fox,jumped,,,over,the,lazy,dog";
//split the string
List<String> list = Arrays.asList(str.split(",", -1));
// add double quotes around each list item and collect it as a comma separated string
String strout = list.stream().collect(Collectors.joining("\",\"", "\"", "\""));
//replace two consecutive double quotes with a empty string
strout = strout.replaceAll("\"\"", "");
System.out.println(strout);
您可以使用 split
并使用 stream
:
public static String covert(String str) {
return Arrays.stream(str.split(","))
.map(s -> s.isEmpty() ? s : '"' + s + '"')
.collect(Collectors.joining(","));
}
然后:
String str = "the,quick,brown,,,,,fox,jumped,,,over,the,lazy,dog";
System.out.println(covert(str));
输出:
"the","quick","brown",,,,,"fox","jumped",,,"over","the","lazy","dog"