Use StringBuilder to pad String with blank spaces or other characters

后端 未结 5 984
别跟我提以往
别跟我提以往 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:10

    Use

    String stars = "*".repeat(i);
    sb.append(stars);
    

    From the javadocs:

    repeat

    public String repeat​(int count) Returns a string whose value is the concatenation of this string repeated count times.

    If this string is empty or count is zero then the empty string is returned.

    Parameters: count - number of times to repeat Returns: A string composed of this string repeated count times or the empty string if this string is empty or count is zero Throws: IllegalArgumentException - if the count is negative. Since: 11

    0 讨论(0)
  • 2020-12-17 17:13

    This can be significantly simplified with Java 11 and it uses array copoy internally, string concatentation should also be converted to stringbuilder internally

    public static String padNum(int number, String pad, int length){
        String numString = String.valueOf(number);
        int padLength = length - numString.length();
        if(padLength > 0)
            return pad.repeat(padLength) + numString;
        else
            return numString;
    }
    

    check if rest is more than 0 to see if we need a pad or not, then use String.repeat to generate a pad of the right size

    the string length will always be >= padLength

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-17 17:24

    Kostronor's approach is awesome, but just for a little bit of different perspetive

    public String pad(String value, int length) {
        return pad(value, length, " ");
    }
    
    public String pad(String value, int length, String with) {
        StringBuilder result = new StringBuilder(length);
        result.append(value);
    
        while (result.length() < length) {
            result.insert(0, with);
        }
    
        return result.toString();
    }
    

    Now you could reverse the idea with result.append(with); to "fill out" a String

    ANOTHER IDEA

    If we want to reduce the possibility of the internal arraycopy causing us any additional overhead (thanks to Kostonor for pointing it out ;)), we could instead do:

    public String fill(int length, String with) {
        StringBuilder sb = new StringBuilder(length);
        while (sb.length() < length) {
            sb.append(with);
        }
        return sb.toString();
    }
    
    public String pad(String value, int length) {
        return pad(value, length, " ");
    }
    
    public String pad(String value, int length, String with) {
        StringBuilder result = new StringBuilder(length);
        // Pre-fill a String value
        result.append(fill(Math.max(0, length - value.length()), with));
        result.append(value);
    
        return result.toString();
    }
    

    The benefit is you gain some additional methods that can be used to build different solutions.

    For example if we include:

    public String fill(String value, int length, String with) {
    
        StringBuilder result = new StringBuilder(length);
        result.append(value);
        result.append(fill(Math.max(0, length - value.length()), with));
    
        return result.toString();
    
    }
    

    And then execute

    System.out.println("PAD: " + pad("Testing", 12, "*"));
    System.out.println("PAD: " + pad("1", 12, "*"));
    System.out.println("FILL: " + fill("1", 12, "*"));
    System.out.println("FILL: " + fill("Testing", 12, "*"));
    

    We get

    PAD: *****Testing
    PAD: ***********1
    FILL: 1***********
    FILL: Testing*****
    

    Thanks to Kostronor for been a good sport and making me think about my ideas a little more ;)

    0 讨论(0)
  • 2020-12-17 17:28

    You can also something really simpler with the fill() method of Arrays.

    StringBuilder sb = new StringBuilder();
    char[] pad = new char[padnum - result.length()];
    Arrays.fill(pad, '*');
    return sb.append(pad).append(result).toString();
    

    We are in really little times but this method is about 25% faster than the for loop one.

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