Create a string with n characters

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

    Just replace your StringBuffer with a StringBuilder. Hard to beat that.

    If your length is a big number, you might implement some more efficient (but more clumsy) self-appendding, duplicating the length in each iteration:

     public static String dummyString(char c, int len) {
      if( len < 1 ) return "";
      StringBuilder sb = new StringBuilder(len).append(c);
      int remnant = len - sb.length();
      while(remnant  > 0) {
       if( remnant  >= sb.length() ) sb.append(sb);
       else sb.append(sb.subSequence(0, remnant));
       remnant  = len - sb.length();
      }
      return sb.toString();
     }
    

    Also, you might try the Arrays.fill() aproach (FrustratedWithFormsDesigner's answer).

提交回复
热议问题