javacharletter

Adding space in Java


So I am trying to practice figure out the quickest and easiest way to add spaces in between the character values.

public static void main(String[] args) {      
        char arr[] = {'g', 'a', 'p', 'e', 't'};
        
        System.out.println("Array: " + new String(arr)); //expected g a p e t
                                                         //instead I got gapet
    }

I tried converting the char values as a string, but I still can't figure out to add spaces in between each letter.


Solution

  • There are a few approaches.

    The simplest would be to use a for-loop.

    String string = "";
    int index = 0;
    for (char character : arr) {
        if (index++ != 0) string += " ";
        string += character;
    }
    

    Or, as others have mentioned, you can use the String#split method, and then use the String#join method.

    String string = String.join(" ", new String(arr).split(""));
    

    You could, also, use a StringBuilder, utilizing the insert method.

    StringBuilder string = new StringBuilder(new String(arr));
    for (int index = string.length() - 1; index >= 0; index--)
        string.insert(index, ' ');
    

    Finally, you could use, with caution, a String#replace.
    Note that, this will place an additional space character at the beginning, and end.
    You can use, String#trim to remove them.

    String string = new String(arr).replace("", " ").trim();