【问题标题】:Enclose each string in a comma separated string in double quotes用双引号将每个字符串括在逗号分隔的字符串中
【发布时间】: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);

【问题讨论】:

标签: java java-stream


【解决方案1】:

你可以使用splitstream

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"

【讨论】:

  • @Holger 也许我没有正确理解您的评论,但是如果您在 .filter(s -&gt;!s.isEmpty()) 前面添加空字符串,您将无法获得所需的输出(您不会获得 ,,, )。如果您使用原始代码.collect(Collectors.joining("\",\"", "\"", "\"")) 考虑到空字符串,您也不会得到所需的输出(即,"","", 而不是,,,)。有什么我想念的吗?
  • 不,这是一个完美的解释。考虑到这些因素,仍然可能存在避免多个字符串连接的流解决方案,但它会比您的更复杂。因此,如果它必须是流解决方案而不是例如replaceAll 变体张贴在问题下方的 cmets 中,您的问题直截了当。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-08-30
  • 1970-01-01
  • 1970-01-01
  • 2016-04-12
  • 2017-12-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多