Create a string with n characters

前端 未结 27 1183
猫巷女王i
猫巷女王i 2020-11-28 22:12

Is there a way in java to create a string with a specified number of a specified character? In my case, I would need to create a string with 10 spaces. My current code is:

27条回答
  •  难免孤独
    2020-11-28 22:51

    Want String to be of fixed size, so you either pad or truncate, for tabulating data...

    class Playground {
        private static String fixStrSize(String s, int n) {
            return String.format("%-" + n + "s", String.format("%." + n +"s", s));
        }
    
        public static void main(String[ ] args) {
            System.out.println("|"+fixStrSize("Hell",8)+"|");
            System.out.println("|"+fixStrSize("Hells Bells Java Smells",8)+"|");
        }
    }
    

    |Hell    |
    |Hells Be|
    

    Excellent reference here.

提交回复
热议问题