Use StringBuilder to pad String with blank spaces or other characters

后端 未结 5 997
别跟我提以往
别跟我提以往 2020-12-17 16:52

I\'m a beginner to java and this is my first post on Stackoverflow. Although my initial code is similar to other posts here, my question relates to implementing StringBuilde

5条回答
  •  旧巷少年郎
    2020-12-17 17:24

    How about simplifying this?

    • padnum is the maximal length of your String
    • result.length is the length already used
    • so you can calculate how many placeholders you need align the string right by substracting the alligned string from the overall size.

      StringBuilder sb = new StringBuilder();
      int rest = padnum - result.length();
      for(int i = 1; i < rest; i++)
          {
               sb.append(" ");
          }
      sb.append(result);
      return sb.toString();
      

    This calculates how many spaces have to be added and adds them. (with a StringBuilder, this is relatively fast) at the end it adds your result.

提交回复
热议问题