Question

I only found this but it's not working, i'll be very thankful if someone helps me because i'm new to java and it's getting me mad lol:

public class ConcatenateStrings {
    public static String concateLines(String[] s, String separator) {
        String result = "";  
        if (s.length > 0) {  
            result = s[0];    // start with the first element  
            for (int i = 1; i < s.length; i++) {  
                StringBuilder sb = new StringBuilder(result);  
                sb.append(separator);  
                sb.append(s[i]);  
                result = sb.toString();
            }
        }
        return result;
    }
}
Was it helpful?

Solution

Don't create a new StringBuilder every time.

public class ConcatenateStrings {
    public static String concateLines(String[] s, String separator) {
        String result = "";  
        StringBuilder sb = new StringBuilder();
        if (s.length > 0) {  
            sb.append(s[0]);
            for (int i = 1; i < s.length; i++) {        
                sb.append(separator);  
                sb.append(s[i]);  
            }
        }
        return sb.toString();
    }
}

public static void main(String[] args) {
 String[] input = {"Test", "input"};
 System.out.println(ConcatenateStrings.concateLines(input, ","));
}

Or with user input:

public static void main(String[] args) {
 System.out.println(ConcatenateStrings.concateLines(args, ","));
}

As you can see, you can even drop the result variable.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top