4

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?

1
  • 2
    are you sure you wanna return this return "string";? Commented Oct 22, 2014 at 21:08

7 Answers 7

9

Nowadays you might want to use:

String.join(separator, strings)

Sign up to request clarification or add additional context in comments.

Comments

4

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.
}

Comments

3

Use Java 8's StringJoiner in combination with the stream API:

String joined = Stream.of(strings).collect(Collectors.joining());

Wrapped in a method, it could look like this:

import java.util.stream.Collectors;
import java.util.stream.Stream;

public static String join(String separator, String... strings) {
    return Stream.of(strings).collect(Collectors.joining(separator));
}

Comments

1

There's plenty of ways, but a StringBuilder is probably the most efficient:

public static String add(String... strings) {
    StringBuilder sb = new StringBuilder();
    for (String arg : strings) {
        sb.append(arg);
    }
    return sb.toString();
}

Basically, you initialise the builder as empty then loop through the arguments appending each one and finally return the contents of the builder.

You probably want to add some code in the loop to handle null values in the arguments (the array won't be null, but strings within it could be. As-is this method would append the string "null" for null values, which may not be what you want.

Comments

0

Try this:

String result;
for (int i =0, i < strings.size(), i++){
 result += strings[i];
}
return result;

2 Comments

It works, but for a large number of strings it would be quite inefficient.
Yes, StringBuilder is better, i just wanted to show other way to concat tis strings.
0

You could use the new Java 8 lambdas and something like,

String[] arr = { "ja", "va" };
Optional<String> result = Arrays.asList(arr).parallelStream()
        .reduce(new BinaryOperator<String>() {
            public String apply(String t, String u) {
                return t + u;
            }
        });
System.out.println(result.get());

Comments

0

To answer your question, this line is what you are doing wrong:

return String.format(arg.concat(arg));

The first time in the for each loop arg would be the string ja. You take that string and concatenat with the same var arg which is ja. Then you return, so you never get into your second run of the loop.

To fix, do what others suggested and use something to collect and join for each variable.

To give you another solution to join, you can try to just join the varargs varible. So you can try:

return String.join ('',strings);

This way, no loop to write, just join the strings. This assumes Java 9.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.