Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concatenate variable arguments of string

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?

like image 729
Ambassador Avatar asked Oct 31 '25 11:10

Ambassador


2 Answers

Nowadays you might want to use:

String.join(separator, strings)

like image 53
membersound Avatar answered Nov 02 '25 01:11

membersound


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.
}
like image 38
Pokechu22 Avatar answered Nov 02 '25 02:11

Pokechu22



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!