Search code examples
javaprintfascii

Spacing problems when printing ASCII colored strings


I was trying to use ASCII colored strings but I had a problem when using printf(%xs ... Problem is that when I add the colors the String space initialization doesnt work anymore. I am using Intellij IDE and I run it in Intellij, so it shouldn't be OS fault.

I've done a short code example to resume my problem:

        System.out.printf("%11s ", "ONE");
        System.out.printf("%11s ","TWO");
        System.out.printf("%11s ","THREE");

        System.out.println();

        System.out.printf("%11s ", "\u001B[37m" + "ONE" + "\u001B[0m");
        System.out.printf("%11s ", "\u001B[37m" + "TWO" + "\u001B[0m");
        System.out.printf("%11s ", "\u001B[37m" + "THREE" + "\u001B[0m");

which prints

        ONE         TWO       THREE 
ONE TWO THREE 

so in the first ones the string print size initialization is correctly applied but when I add colors it doesnt work anymore, can someone help me ?


Solution

  • You're printing 12 characters in an 11-character output field. There is no padding to be done, so no padding is done.

    %11s means "11 characters", not "11 characters that happen to occupy visible pixels on the screen and never mind about the others".

    You could increase the field width, but I think it better to use separate arguments for the parts that are not part of the padded field.

    Use something like this:

    System.out.printf("%s%11s%s ", "\u001B[37m", "ONE", "\u001B[0m");