【发布时间】:2022-01-13 17:19:31
【问题描述】:
我正在处理一个要求,即我需要将单个字符串括在双引号中的逗号分隔字符串中,同时保留空字符串。
例如:字符串 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);
【问题讨论】:
-
您可以使用正则表达式在一行中执行此操作:
String strout = str.replaceAll("(\\w+)", "\"$1\"");来源:Re-add strings with qoutations - Mason Smith -
如果使用 encodeURI (stackoverflow.com/questions/607176/…),您正在做的事情会更安全/更强大
-
str.replaceAll("[^,]+", "\"$0\"")
标签: java java-stream