How to add spaces to left and right of chars in a string in java?

I’m trying to print out a string with spaces on either side of each char in the string

so if I have String s = “abcde”

it would create something like this a b c d e with a space before the first char and three between each char.

I just haven’t been able to find a way to do this with my knowledge.

Answer

A super simple example, that doesn’t handle a multitude of potential input scenarios.

    public static void main(String[] args)
    {
        String s = "abcde";
        
        
        for (int i = 0; i < s.length(); ++i) {
            System.out.print("_" + s.charAt(i));
        }
        System.out.println("_");
    }

NOTE: used an underscore rather than a space in order to allow visual check of the output.

Sample output:

_a_b_c_d_e_

Rather than direct output, one could use a StringBuilder and .append to a builder instead, for example.

Using StringBuilder:

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length(); ++i) {
            sb.append('_').append(s.charAt(i));
        }
        sb.append('_');        
        
        System.out.println(sb.toString());

Based on a comment where the desired output is slightly different (two internal spaces, one leading and trailing space), this suggests an alternative approach:

   public static String addSpace(String inp) {
        StringBuilder sB = new StringBuilder();
        
        String string = inp.trim();
        
        String div = "___";  // spaces, or whatever
        
        
        sB.append('_');  // add leading space
        for(int index = 0; index < string.length(); ++index) {
            sB.append(string.charAt(index))
                .append(div);  // two spaces  
         }
        sB.setLength(sB.length() - (div.length() - 1) );
        
        return (sB.toString());
    }

NOTE: again using an underscore to allow for easier debugging.

Output when div is set to 3 underscores (or spaces):

_0___0___0___1___0___1___1___0_

Leave a Reply

Your email address will not be published. Required fields are marked *