Generate fixed length Strings filled with whitespaces

后端 未结 13 980
借酒劲吻你
借酒劲吻你 2020-12-04 13:52

I need to produce fixed length string to generate a character position based file. The missing characters must be filled with space character.

As an example, the fi

13条回答
  •  庸人自扰
    2020-12-04 14:35

    Utilize String.format's padding with spaces and replace them with the desired char.

    String toPad = "Apple";
    String padded = String.format("%8s", toPad).replace(' ', '0');
    System.out.println(padded);
    

    Prints 000Apple.


    Update more performant version (since it does not rely on String.format), that has no problem with spaces (thx to Rafael Borja for the hint).

    int width = 10;
    char fill = '0';
    
    String toPad = "New York";
    String padded = new String(new char[width - toPad.length()]).replace('\0', fill) + toPad;
    System.out.println(padded);
    

    Prints 00New York.

    But a check needs to be added to prevent the attempt of creating a char array with negative length.

提交回复
热议问题