Adding 0's to string/int variable

前端 未结 3 827
遥遥无期
遥遥无期 2021-01-15 08:42

So I have been working on a naming convention which add 0\'s before a string. I\'m trying to do this the short handed way before breaking everything into if statements. Here

相关标签:
3条回答
  • 2021-01-15 08:51

    Assuming that n is a String that represents a number, or more generally that n doesn't have any space characters:

    String.format("%5s",n).replace(" ","0");
    
    0 讨论(0)
  • 2021-01-15 09:04

    How about this?

    ("00000" + numberAsString).substring(numberAsString.length())
    

    This will only work if you have 5 or less digit numbers.

    Ideone link to check code

    Reference

    To be honest, I also think 4 times how this code works, but after understanding I posted as this is something out of the box.

    0 讨论(0)
  • 2021-01-15 09:10

    Not sure if it's the best way, but that's what I use.

    public static String pad (String input, char with, int desiredLength)
    {
        if (input.length() >= desiredLength) {
            return input;
        }
        StringBuilder output = new StringBuilder (desiredLength);
        for (int i = input.length (); i < desiredLength; i++) {
            output.append (with);
        }
        output.append (input);
    
        return output.toString();
    }
    

    Usage (assuming the static method is in a class called Utils) :

    System.out.println (Utils.pad(myString,'0',10));
    

    EDIT : generalized to any input String, character to pad with, and desired output length.

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