Java - 将引号附加到数组中的字符串并连接数组中的字符串 [英] Java - Append quotes to strings in an array and join strings in an array

查看:31
本文介绍了Java - 将引号附加到数组中的字符串并连接数组中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将双引号附加到数组中的字符串,然后将它们作为单个字符串加入(保留引号).是否有任何字符串库可以做到这一点?我已经尝试过 Apache commons StringUtils.join 和 Google guava 中的 Joiner 类,但找不到任何附加双引号的内容.

I would like to append double quotes to strings in an array and then later join them as a single string (retaining the quotes). Is there any String library which does this? I have tried Apache commons StringUtils.join and the Joiner class in Google guava but couldn't find anything that appends double quotes.

我的输入将是如下所述的数组:

My input would be an array as mentioned below:

String [] listOfStrings = {"day", "campaign", "imps", "conversions"};

所需的输出应如下所述:

Required output should be as mentioned below:

String output = "\"day\", \"campaign\", \"imps\", \"conversions\"";

我知道我可以遍历数组并附加引号.但如果有的话,我想要一个更简洁的解决方案.

I know I can loop through the array and append quotes. But I would like a more cleaner solution if there is one.

推荐答案

使用 Java 8+

Java 8 具有 Collectors.joining() 及其重载.它还有 String.join.

具有可重复使用的功能

Function<String,String> addQuotes = s -> "\"" + s + "\"";

String result = listOfStrings.stream()
  .map(addQuotes)
  .collect(Collectors.joining(", "));

没有任何可重用的功能

String result = listOfStrings.stream()
  .map(s -> "\"" + s + "\"")
  .collect(Collectors.joining(", "));

最短的(虽然有点hackish)

Shortest (somewhat hackish, though)

String result = listOfStrings.stream()
  .collect(Collectors.joining("\", \"", "\"", "\""));

使用String.join

非常黑客.不要在名为 wrapWithQuotesAndJoin 的方法中使用.

String result = listOfString.isEmpty() ? "" : "\"" + String.join("\", \"", listOfStrings) + "\"";

使用旧版本的 Java

帮自己一个忙,使用图书馆.Guava立刻浮现在脑海中.

Function<String,String> addQuotes = new Function<String,String>() {
  @Override public String apply(String s) {
    return new StringBuilder(s.length()+2).append('"').append(s).append('"').toString();
  }
};
String result = Joiner.on(", ").join(Iterables.transform(listOfStrings, addQuotes));

没有图书馆

String result;
if (listOfStrings.isEmpty()) {
  result = "";
} else {
  StringBuilder sb = new StringBuilder();
  Iterator<String> it = listOfStrings.iterator();
  sb.append('"').append(it.next()).append('"'); // Not empty
  while (it.hasNext()) {
    sb.append(", \"").append(it.next()).append('"');
  }
  result = sb.toString();
}

注意:所有的解决方案都假设 listOfStrings 是一个 List 而不是 String[]>.您可以使用 Arrays.asList(arrayOfStrings)String[] 转换为 List.您可以使用 Arrays.stream(arrayOfString) 直接从 String[] 获取 Stream.

Note: all the solutions assume that listOfStrings is a List<String> rather than a String[]. You can convert a String[] into a List<String> using Arrays.asList(arrayOfStrings). You can get a Stream<String> directly from a String[] using Arrays.stream(arrayOfString).

这篇关于Java - 将引号附加到数组中的字符串并连接数组中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆