Create a string with n characters

前端 未结 27 1101
猫巷女王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:36

    how about this?

    public String fillSpaces(int len) {
        /* the spaces string should contain spaces exceeding the max needed */  
        String spaces = "                                                   ";
        return spaces.substring(0,len);
    }
    

    EDIT: I've written a simple code to test the concept and here what i found.

    Method 1: adding single space in a loop:

      public String execLoopSingleSpace(int len){
        StringBuilder sb = new StringBuilder();
    
        for(int i=0; i < len; i++) {
            sb.append(' ');
        }
    
        return sb.toString();
      }
    

    Method 2: append 100 spaces and loop, then substring:

      public String execLoopHundredSpaces(int len){
        StringBuilder sb = new StringBuilder("          ")
                .append("          ").append("          ").append("          ")
                .append("          ").append("          ").append("          ")
                .append("          ").append("          ").append("          ");
    
        for (int i=0; i < len/100 ; i++) {
            sb.append("          ")
                .append("          ").append("          ").append("          ")
                .append("          ").append("          ").append("          ")
                .append("          ").append("          ").append("          ");
        }
    
        return sb.toString().substring(0,len);
      }
    

    The result I get creating 12,345,678 spaces:

    C:\docs\Projects> java FillSpace 12345678
    method 1: append single spaces for 12345678 times. Time taken is **234ms**. Length of String is 12345678
    method 2: append 100 spaces for 123456 times. Time taken is **141ms**. Length of String is 12345678
    Process java exited with code 0
    

    and for 10,000,000 spaces:

    C:\docs\Projects> java FillSpace 10000000
    method 1: append single spaces for 10000000 times. Time taken is **157ms**. Length of String is 10000000
    method 2: append 100 spaces for 100000 times. Time taken is **109ms**. Length of String is 10000000
    Process java exited with code 0
    

    combining direct allocation and iteration always takes less time, on average 60ms less when creating huge spaces. For smaller sizes, both results are negligible.

    But please continue to comment :-)

提交回复
热议问题