Create a string with n characters

前端 未结 27 952
猫巷女王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 23:00

    Have a method like this. This appends required spaces at the end of the given String to make a given String to length of specific length.

    public static String fillSpaces (String str) {
    
        // the spaces string should contain spaces exceeding the max needed
        String spaces = "                                                   ";
        return str + spaces.substring(str.length());
    }
    
    0 讨论(0)
  • 2020-11-28 23:01

    Likely the shortest code using the String API, exclusively:

    String space10 = new String(new char[10]).replace('\0', ' ');
    
    System.out.println("[" + space10 + "]");
    // prints "[          ]"
    

    As a method, without directly instantiating char:

    import java.nio.CharBuffer;
    
    /**
     * Creates a string of spaces that is 'spaces' spaces long.
     *
     * @param spaces The number of spaces to add to the string.
     */
    public String spaces( int spaces ) {
      return CharBuffer.allocate( spaces ).toString().replace( '\0', ' ' );
    }
    

    Invoke using:

    System.out.printf( "[%s]%n", spaces( 10 ) );
    
    0 讨论(0)
  • 2020-11-28 23:01

    If you want only spaces, then how about:

    String spaces = (n==0)?"":String.format("%"+n+"s", "");
    

    which will result in abs(n) spaces;

    0 讨论(0)
提交回复
热议问题