2

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 I print 0's before an int giving me an answer of 00005.

String test = null;
int n = 5;
test = String.format("%05d%n", n);  
System.out.println(test);

Now what I would like to do is do this to a String. So for example if String n = "5"; it would give me an answer of 00005 and if String n = "20"; it would be 00020. I do not wish to use the integer method to change the string to and int, and back into a string. Any help would be appreciated. Thank you!

3 Answers3

5

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.

Eran
  • 387,369
  • 54
  • 702
  • 768
2

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.

Community
  • 1
  • 1
Fahim Parkar
  • 30,974
  • 45
  • 160
  • 276
  • 2
    `Math.min(numberAsString.length(),5)`? Then you could get rid of the restriction. – ajb Jul 29 '14 at 21:53
  • @ajb : Right... But I wrote note just to inform OP as he is looking for 5 digit only... If OP want to increase for more width, OP will add additional 0's in the code itself... – Fahim Parkar Jul 29 '14 at 21:55
0

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");
ajb
  • 31,309
  • 3
  • 58
  • 84
  • 1
    That only works if the original String has no spaces, which is true if the String represents a number, but doesn't work for arbitrary Strings. – Eran Jul 29 '14 at 21:39
  • 1
    @Eran Right, I assumed it represented a number. I can't think of a case where you'd want to do this otherwise. – ajb Jul 29 '14 at 21:40
  • You could fix it by using n.trim() in the format statement ;) ... It's possible that the String value may come from at her source, file, web service or been sub-stringed in some way, so it's nice to "ensure" an accurate value ;) – MadProgrammer Jul 29 '14 at 21:56