I need to concatenate a variable number of arguments (type String) to one String:
E.g.:
System.out.println( add("ja", "va") );
should return java but my implementation returns jaja.
I tried this:
public static String add(String... strings) {
for (String arg : strings) {
return String.format(arg.concat(arg));
}
return "string";
}
What am I doing wrong?
Nowadays you might want to use:
String.join(separator, strings)
You're returning on the first iteration of the loop (return String.format ...) rather than at the end. What you should use here is a StringBuilder:
public static String add(String... strings) {
StringBuilder builder = new StringBuilder();
for (String arg : strings) {
builder.append(arg);
}
return builder.toString(); //Outputs the entire contents of the StringBuilder.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With