Soon Kwon Soon Kwon - 2 months ago 8
Java Question

joining array of strings + a separator

java noob here...

This is driving me nuts because I know it's something so simple but I have been working on this for 30 mins...

this is from codefights:

For arguments = ["Code", "Fight", "On", "!"] and separator = "/", the output should be
myConcat(arguments, separator) = "Code/Fight/On/!/".

my code:

String myConcat(String[] arguments, String separator) {
for(int i = 0; i <= arguments.length; i++){
String output = arguments[0] + separator;
}
return output;
}


error: file.java on line 5: error: cannot find symbol
return output;
^
symbol: variable output
location: class _runfniek
1 error

any tips would be greatly appreciated...

Answer

First, StringBuilder is prefered than + operation.

Second, it is a mistake to define String output in the loop body which does not save the value actually.

Third, need consider the border, i.e. no separator should be appended for the last element of the argument array.

Fourth, it is i < arguments.length, not i <= arguments.length

String myConcat(String[] arguments, String separator) {
    StringBuilder output = new StringBuilder();
    for(int i = 0; i < arguments.length; i++){
        output.append(arguments[i]);
        if(i < arguments.length-1){ 
             output.append(separator);
        }
        return output.toString();
    }