Java - 将引号附加到数组中的字符串并连接数组中的字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18227938/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java - Append quotes to strings in an array and join strings in an array
提问by Anand
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.
我想将双引号附加到数组中的字符串,然后将它们作为单个字符串加入(保留引号)。是否有任何字符串库可以做到这一点?我已经尝试过 Apache commons StringUtils.join 和 Google guava 中的 Joiner 类,但找不到任何附加双引号的东西。
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.
我知道我可以遍历数组并附加引号。但如果有的话,我想要一个更清洁的解决方案。
采纳答案by Olivier Grégtheitroade
With Java 8+
使用 Java 8+
Java 8 has Collectors.joining()
and its overloads. It also has String.join
.
Java 8Collectors.joining()
及其重载。它也有String.join
。
Using a Stream
and a Collector
使用一个Stream
和一个Collector
With a reusable function
具有可重复使用的功能
Function<String,String> addQuotes = s -> "\"" + s + "\"";
String result = listOfStrings.stream()
.map(addQuotes)
.collect(Collectors.joining(", "));
Without any reusable function
没有任何可重用的功能
String result = listOfStrings.stream()
.map(s -> "\"" + s + "\"")
.collect(Collectors.joining(", "));
Shortest(somewhat hackish, though)
最短的(虽然有点hackish)
String result = listOfStrings.stream()
.collect(Collectors.joining("\", \"", "\"", "\""));
Using String.join
使用 String.join
Very hackish. Don't use except in a method called wrapWithQuotesAndJoin
.
非常黑客。不要在名为wrapWithQuotesAndJoin
.
String result = listOfString.isEmpty() ? "" : "\"" + String.join("\", \"", listOfStrings) + "\"";
With older versions of Java
使用旧版本的 Java
Do yourself a favor and use a library. Guavacomes immediately to mind.
帮自己一个忙,使用图书馆。立即想到番石榴。
Using 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));
No libraries
没有图书馆
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();
}
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)
.
注意:所有解决方案都假定listOfStrings
是 aList<String>
而不是 a String[]
。您可以将 aString[]
转换为List<String>
using Arrays.asList(arrayOfStrings)
。您可以Stream<String>
直接从String[]
using 获取Arrays.stream(arrayOfString)
。
回答by bas
You can create the code for this functionality yourself as well:
您也可以自己为此功能创建代码:
String output = "";
for (int i = 0; i < listOfStrings.length; i++)
{
listOfStrings[i] = "\"" + listOfStrings[i] + "\"";
output += listOfStrings[i] + ", ";
}
回答by Sommes
public static void main(String[] args) {
// TODO code application logic here
String [] listOfStrings = {"day", "campaign", "imps", "conversions"};
String output = "";
for (int i = 0; i < listOfStrings.length; i++) {
output += "\"" + listOfStrings[i] + "\"";
if (i != listOfStrings.length - 1) {
output += ", ";
}
}
System.out.println(output);
}
Output: "day", "campaign", "imps", "conversions"
输出:“day”、“campaign”、“imps”、“conversions”
回答by Himanshu Mishra
There is no method present in JDK which can do this, but you can use the Apache Commons LangsStringUtlsclass , StringUtils.join()
it will work
JDK 中没有可以执行此操作的方法,但是您可以使用Apache Commons Langs StringUtls类,StringUtils.join()
它会起作用
回答by Sifeng
String output = "\"" + StringUtils.join(listOfStrings , "\",\"") + "\"";
回答by John Rumpel
A more generic way would be sth. like:
更通用的方法是…… 喜欢:
private static class QuoteFunction<F> {
char quote;
public QuoteFunction(char quote) {
super();
this.quote = quote;
}
Function<F, String> func = new Function<F,String>() {
@Override
public String apply(F s) {
return new StringBuilder(s.toString().length()+2).append(quote).append(s).append(quote).toString();
}
};
public Function<F, String> getFunction() {
return func;
}
}
... call it via the following function
...通过以下函数调用它
public static <F> String asString(Iterable<F> lst, String delimiter, Character quote) {
QuoteFunction<F> quoteFunc = new QuoteFunction<F>(quote);
Joiner joiner = Joiner.on(delimiter).skipNulls();
return joiner.join(Iterables.transform(lst, quoteFunc.getFunction()));
}
回答by Kevin Peterson
Add the quotes along with the separator and then append the quotes to the front and back.
添加引号和分隔符,然后将引号附加到前后。
"\"" + Joiner.on("\",\"").join(values) + "\""