Java-Añadir comillas a cadenas en un array y unir cadenas en un array
Me gustaría añadir comillas dobles a cadenas en una matriz y luego unirlas como una sola cadena (conservando las comillas). ¿Hay alguna librería de cadenas que haga esto? He probado Apache commons StringUtils.unirse y la clase Joiner en Google guava, pero no pudo encontrar nada que agregue comillas dobles.
Mi entrada sería una matriz como se menciona a continuación:
String [] listOfStrings = {"day", "campaign", "imps", "conversions"};
La salida requerida debe ser la que se menciona a continuación:
String output = "\"day\", \"campaign\", \"imps\", \"conversions\"";
Sé que puedo recorrer el array y añadir comillas. Pero me gustaría una solución más limpia si la hay.
7 answers
Con Java 8 +
Java 8 tiene Collectors.joining()
y sus sobrecargas. También tiene String.join
.
Usando a Stream
y a Collector
Con una función reutilizable
Function<String,String> addQuotes = s -> "\"" + s + "\"";
String result = listOfStrings.stream()
.map(addQuotes)
.collect(Collectors.joining(", "));
Sin ninguna función reutilizable
String result = listOfStrings.stream()
.map(s -> "\"" + s + "\"")
.collect(Collectors.joining(", "));
Más corto (algo hackish, aunque)
String result = listOfStrings.stream()
.collect(Collectors.joining("\", \"", "\"", "\""));
Usando String.join
Muy hackish. No utilice excepto en un método llamado wrapWithQuotesAndJoin
.
String result = listOfString.isEmpty() ? "" : "\"" + String.join("\", \"", listOfStrings) + "\"";
Con versiones anteriores de Java
Hazte un favor y usa una biblioteca. La guayaba viene inmediatamente a la mente.
Usando Guayaba
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 hay bibliotecas
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();
}
Nota : todas las soluciones asumen que listOfStrings
es un List<String>
en lugar de un String[]
. Puede convertir un String[]
en un List<String>
usando Arrays.asList(arrayOfStrings)
. Puedes obtener un Stream<String>
directamente desde un String[]
usando Arrays.stream(arrayOfString)
.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-18 11:37:25
String output = "\"" + StringUtils.join(listOfStrings , "\",\"") + "\"";
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-26 08:59:34
Agregue las comillas junto con el separador y luego agregue las comillas al anverso y al reverso.
"\"" + Joiner.on("\",\"").join(values) + "\""
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-14 21:14:33
También puede crear el código para esta funcionalidad:
String output = "";
for (int i = 0; i < listOfStrings.length; i++)
{
listOfStrings[i] = "\"" + listOfStrings[i] + "\"";
output += listOfStrings[i] + ", ";
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-08-14 09:31:57
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);
}
Salida:" día"," campaña"," imps","conversiones"
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-08-14 09:36:45
No hay ningún método presente en JDK que pueda hacer esto, pero puede usar el Apache Commons Langs StringUtls clase, StringUtils.join()
funcionará
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-08-14 09:43:14
Una forma más genérica sería sth. como:
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;
}
}
... llámelo a través de la siguiente función
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()));
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-08-29 12:28:16