Use StringBuilder to pad String with blank spaces or other characters

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

提交回复
热议问题