Create a string with n characters

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

    You can replace StringBuffer with StringBuilder ( the latter is not synchronized, may be a faster in a single thread app )

    And you can create the StringBuilder instance once, instead of creating it each time you need it.

    Something like this:

    class BuildString {
         private final StringBuilder builder = new StringBuilder();
         public String stringOf( char c , int times ) {
    
             for( int i = 0 ; i < times ; i++  ) {
                 builder.append( c );
             }
             String result = builder.toString();
             builder.delete( 0 , builder.length() -1 );
             return result;
          }
    
      }
    

    And use it like this:

     BuildString createA = new BuildString();
     String empty = createA.stringOf( ' ', 10 );
    

    If you hold your createA as a instance variable, you may save time creating instances.

    This is not thread safe, if you have multi threads, each thread should have its own copy.

提交回复
热议问题