How can I pad a String in Java?












373















Is there some easy way to pad Strings in Java?



Seems like something that should be in some StringUtil-like API, but I can't find anything that does this.










share|improve this question

























  • On the issue of the apache function vs the string formatter there is little doubt that the apache function is more clear and easy to read. Wrapping the formatter in function names isn't ideal.

    – Terra Caines
    Jul 8 '10 at 2:24
















373















Is there some easy way to pad Strings in Java?



Seems like something that should be in some StringUtil-like API, but I can't find anything that does this.










share|improve this question

























  • On the issue of the apache function vs the string formatter there is little doubt that the apache function is more clear and easy to read. Wrapping the formatter in function names isn't ideal.

    – Terra Caines
    Jul 8 '10 at 2:24














373












373








373


89






Is there some easy way to pad Strings in Java?



Seems like something that should be in some StringUtil-like API, but I can't find anything that does this.










share|improve this question
















Is there some easy way to pad Strings in Java?



Seems like something that should be in some StringUtil-like API, but I can't find anything that does this.







java string padding






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Sep 21 '11 at 17:20









Jason Plank

2,14442738




2,14442738










asked Dec 23 '08 at 9:15









pvgoddijnpvgoddijn

4,923123752




4,923123752













  • On the issue of the apache function vs the string formatter there is little doubt that the apache function is more clear and easy to read. Wrapping the formatter in function names isn't ideal.

    – Terra Caines
    Jul 8 '10 at 2:24



















  • On the issue of the apache function vs the string formatter there is little doubt that the apache function is more clear and easy to read. Wrapping the formatter in function names isn't ideal.

    – Terra Caines
    Jul 8 '10 at 2:24

















On the issue of the apache function vs the string formatter there is little doubt that the apache function is more clear and easy to read. Wrapping the formatter in function names isn't ideal.

– Terra Caines
Jul 8 '10 at 2:24





On the issue of the apache function vs the string formatter there is little doubt that the apache function is more clear and easy to read. Wrapping the formatter in function names isn't ideal.

– Terra Caines
Jul 8 '10 at 2:24












27 Answers
27






active

oldest

votes


















158














Apache StringUtils has several methods: leftPad, rightPad, center and repeat.



But please note that — as others have mentioned and demonstrated in this answer — String.format() and the Formatter classes in the JDK are better options. Use them over the commons code.






share|improve this answer





















  • 79





    java.util.Formatter (and String.format()) does this. Always prefer the JDK to an external library if the JDK version does the job (which it does).

    – cletus
    Dec 23 '08 at 12:02






  • 6





    For several reasons, I'd now prefer Guava to Apache Commons; this answer shows how to do it in Guava.

    – Jonik
    Oct 24 '12 at 12:37








  • 1





    @Jonik would you care to list some of your reasons? The APIs look pretty much the same.

    – glen3b
    May 18 '14 at 5:18






  • 3





    @glen3b: For an individual utility, like these string padding helpers, it really makes no difference which lib to use. That said, Guava is overall a more modern, cleaner and better documented lib than its counterparts in various Apache Commons projects (Commons Lang, Commons Collections, Commons IO, etc). It's also built by really smart guys (Kevin Bourrillion et al), many of whom are active at SO. Myself I ended up replacing the various Apache Commons libs with just Guava years ago, and have had no regrets.

    – Jonik
    May 18 '14 at 18:59








  • 3





    @glen3b: Some good further reading at this question.

    – Jonik
    May 18 '14 at 19:00





















566














Since Java 1.5, String.format() can be used to left/right pad a given string.



public static String padRight(String s, int n) {
return String.format("%-" + n + "s", s);
}

public static String padLeft(String s, int n) {
return String.format("%" + n + "s", s);
}

...

public static void main(String args) throws Exception {
System.out.println(padRight("Howto", 20) + "*");
System.out.println(padLeft("Howto", 20) + "*");
}


And the output is:



Howto               *
Howto*





share|improve this answer





















  • 33





    What if you need to lpad with other chars (not spaces) ? Is it still possible with String.format ? I am not able to make it work...

    – Guido
    Aug 11 '09 at 15:48






  • 6





    AFAIK String.format() can't do that but it's not too difficult to code it, see rgagnon.com/javadetails/java-0448.html (2nd example)

    – RealHowTo
    Dec 7 '09 at 14:47






  • 61





    @Nullw0rm, if you're referring to rgagnon.com, be aware that RealHowTo is the author of rgagnon.com too, so he would be crediting himself...

    – Colin Pickard
    Nov 12 '10 at 14:17






  • 3





    at least on my JVM, the "#" doesn't work, the "-" is fine. (Just delete the #). This may be consistent with the formatter documentation, I dunno; it says "'#' 'u0023' Requires the output use an alternate form. The definition of the form is specified by the conversion."

    – gatoatigrado
    Jan 2 '11 at 21:25








  • 6





    Thanks for the awesome answer. I have a doubt though, what is the 1$ for? @leo has made a very similar answer that doesn't use 1$ and it apparently has the same effect. Does it make a difference?

    – Fabrício Matté
    Mar 8 '13 at 19:14





















234














Padding to 10 characters:



String.format("%10s", "foo").replace(' ', '*');
String.format("%-10s", "bar").replace(' ', '*');
String.format("%10s", "longer than 10 chars").replace(' ', '*');


output:



  *******foo
bar*******
longer*than*10*chars


Display '*' for characters of password:



String password = "secret123";
String padded = String.format("%"+password.length()+"s", "").replace(' ', '*');


output has the same length as the password string:



  secret123
*********





share|improve this answer



















  • 43





    Just as long as we all remember not to pass in a string with spaces... :D

    – aboveyou00
    Jan 18 '13 at 3:20






  • 4





    I'm with @aboveyou00--this is a horrendous solution for strings with spaces, including the example provided by leo. A solution for padding a string on the left or the right should not alter the input string as it appears in the output, unless the input string's original padding causes it to exceed the specified padding length.

    – Brian Warshaw
    Jan 29 '15 at 16:24






  • 2





    Acknowledge the space issue. .replace(' ', '*') was rather intended to show the effect of padding. The password hiding expression does not have this issue anyway... For a better answer on customizing the left and right padding string using native Java feature see my other answer.

    – leo
    Aug 31 '17 at 21:12











  • If the string contains only single spaces and you want to pad with different characters, you can use regex replace with look behind/ahead: String.format("%30s", "pad left").replaceAll("(?<=( |^)) ", "*") or String.format("%-30s", "pad right").replaceAll(" (?=( |$))", "*")

    – Jaroslaw Pawlak
    Jun 26 '18 at 11:01



















86














In Guava, this is easy:



Strings.padStart("string", 10, ' ');
Strings.padEnd("string", 10, ' ');





share|improve this answer



















  • 9





    +1. In any sensible modern Java project, this is the correct solution. :-)

    – Jonik
    Oct 24 '12 at 12:34






  • 4





    My java assignment is not sensible then

    – Ben Winding
    Aug 29 '18 at 14:43



















29














Something simple:



The value should be a string. convert it to string, if it's not. Like "" + 123 or Integer.toString(123)



// let's assume value holds the String we want to pad
String value = "123";


Substring start from the value length char index until end length of padded:



String padded="00000000".substring(value.length()) + value;

// now padded is "00000123"


More precise



pad right:



String padded = value + ("ABCDEFGH".substring(value.length())); 

// now padded is "123DEFGH"


pad left:



String padString = "ABCDEFGH";
String padded = (padString.substring(0, padString.length() - value.length())) + value;

// now padded is "ABCDE123"





share|improve this answer





















  • 3





    Simple answer made over confusable. Atleast use 2 different variables names. I bet, you missed few upvotes, because people couldn't digest this quickly...

    – mtk
    Oct 17 '14 at 7:27











  • thanks, i have updated to a more explained version.

    – Shimon Doodkin
    Oct 17 '14 at 8:58











  • m02ph3u5 - thank you for editing

    – Shimon Doodkin
    Jun 4 '16 at 11:07



















22














Have a look at org.apache.commons.lang.StringUtils#rightPad(String str, int size, char padChar).



But the algorithm is very simple (pad right up to size chars):



public String pad(String str, int size, char padChar)
{
StringBuffer padded = new StringBuffer(str);
while (padded.length() < size)
{
padded.append(padChar);
}
return padded.toString();
}





share|improve this answer



















  • 11





    Note that as of Java 1.5 it's worth using StringBuilder instead of StringBuffer.

    – Jon Skeet
    Dec 23 '08 at 9:34






  • 1





    You are right, it would be better to use if Java 5 is set.

    – Arne Burmeister
    Dec 23 '08 at 22:00



















21














Besides Apache Commons, also see String.format which should be able to take care of simple padding (e.g. with spaces).






share|improve this answer































    16














    public static String LPad(String str, Integer length, char car) {
    return (str + String.format("%" + length + "s", "").replace(" ", String.valueOf(car))).substring(0, length);
    }

    public static String RPad(String str, Integer length, char car) {
    return (String.format("%" + length + "s", "").replace(" ", String.valueOf(car)) + str).substring(str.length(), length + str.length());
    }

    LPad("Hi", 10, 'R') //gives "RRRRRRRRHi"
    RPad("Hi", 10, 'R') //gives "HiRRRRRRRR"
    RPad("Hi", 10, ' ') //gives "Hi "
    RPad("Hi", 1, ' ') //gives "H"
    //etc...





    share|improve this answer





















    • 4





      Pay attention: you inverted functions names; if you run it you'll see.

      – bluish
      Feb 10 '12 at 7:52











    • plus if the original str contains spaces then this doesn't work

      – Steven Shaw
      Sep 27 '12 at 8:34











    • @StevenShaw If I'm not mistaken, the replace does not target the original str, so this is correct.

      – mafu
      Jun 22 '14 at 23:08






    • 3





      By convention you should not use a capital letter for function names.

      – principal-ideal-domain
      Aug 20 '14 at 12:04











    • Is there a missing conditional on returning the string as is when (length - str.length()) is 0? The formatter throws a FormatFlagsConversionMismatchException when %0s is the format string.

      – Devin Walters
      Jun 8 '18 at 17:16



















    7














    This took me a little while to figure out.
    The real key is to read that Formatter documentation.



    // Get your data from wherever.
    final byte data = getData();
    // Get the digest engine.
    final MessageDigest md5= MessageDigest.getInstance("MD5");
    // Send your data through it.
    md5.update(data);
    // Parse the data as a positive BigInteger.
    final BigInteger digest = new BigInteger(1,md5.digest());
    // Pad the digest with blanks, 32 wide.
    String hex = String.format(
    // See: http://download.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html
    // Format: %[argument_index$][flags][width]conversion
    // Conversion: 'x', 'X' integral The result is formatted as a hexadecimal integer
    "%1$32x",
    digest
    );
    // Replace the blank padding with 0s.
    hex = hex.replace(" ","0");
    System.out.println(hex);





    share|improve this answer
























    • Why make the end so complicated? You could have just done String hex = String.format("%032x", digest); and had the exact same results, just without a needless replace() and having to use the $ to access specific variables (there's only one, after all.)

      – ArtOfWarfare
      Oct 17 '12 at 17:37











    • @ArtOfWarfare fair point. Someone originally asked for padding hex values in another question, I saw that I had a link to the formatter documentation. It's complicated for completeness.

      – Nthalk
      Mar 4 '14 at 21:42



















    6














    i know this thread is kind of old and the original question was for an easy solution but if it's supposed to be really fast, you should use a char array.



    public static String pad(String str, int size, char padChar)
    {
    if (str.length() < size)
    {
    char temp = new char[size];
    int i = 0;

    while (i < str.length())
    {
    temp[i] = str.charAt(i);
    i++;
    }

    while (i < size)
    {
    temp[i] = padChar;
    i++;
    }

    str = new String(temp);
    }

    return str;
    }


    the formatter solution is not optimal. just building the format string creates 2 new strings.



    apache's solution can be improved by initializing the sb with the target size so replacing below



    StringBuffer padded = new StringBuffer(str); 


    with



    StringBuffer padded = new StringBuffer(pad); 
    padded.append(value);


    would prevent the sb's internal buffer from growing.






    share|improve this answer
























    • If the StringBuffer can't be accessed by multiple threads at once (which in this case is true), you should use a StringBuilder (in JDK1.5+) to avoid the overhead of synchronization.

      – glen3b
      May 20 '14 at 23:40



















    5














    Here is another way to pad to the right:



    // put the number of spaces, or any character you like, in your paddedString

    String paddedString = "--------------------";

    String myStringToBePadded = "I like donuts";

    myStringToBePadded = myStringToBePadded + paddedString.substring(myStringToBePadded.length());

    //result:
    myStringToBePadded = "I like donuts-------";





    share|improve this answer

































      4














      You can reduce the per-call overhead by retaining the padding data, rather than rebuilding it every time:



      public class RightPadder {

      private int length;
      private String padding;

      public RightPadder(int length, String pad) {
      this.length = length;
      StringBuilder sb = new StringBuilder(pad);
      while (sb.length() < length) {
      sb.append(sb);
      }
      padding = sb.toString();
      }

      public String pad(String s) {
      return (s.length() < length ? s + padding : s).substring(0, length);
      }

      }


      As an alternative, you can make the result length a parameter to the pad(...) method. In that case do the adjustment of the hidden padding in that method instead of in the constructor.



      (Hint: For extra credit, make it thread-safe! ;-)






      share|improve this answer



















      • 1





        That is thread safe, except for unsafe publication (make your fields final, as a matter of course). I think performance could be improved by doing a substring before the + which should be replaced by concat (strangely enough).

        – Tom Hawtin - tackline
        Dec 24 '08 at 12:44



















      2














      you can use the built in StringBuilder append() and insert() methods,
      for padding of variable string lengths:



      AbstractStringBuilder append(CharSequence s, int start, int end) ;


      For Example:



      private static final String  MAX_STRING = "                    "; //20 spaces

      Set<StringBuilder> set= new HashSet<StringBuilder>();
      set.add(new StringBuilder("12345678"));
      set.add(new StringBuilder("123456789"));
      set.add(new StringBuilder("1234567811"));
      set.add(new StringBuilder("12345678123"));
      set.add(new StringBuilder("1234567812234"));
      set.add(new StringBuilder("1234567812222"));
      set.add(new StringBuilder("12345678122334"));

      for(StringBuilder padMe: set)
      padMe.append(MAX_STRING, padMe.length(), MAX_STRING.length());





      share|improve this answer































        2














        This works:



        "".format("%1$-" + 9 + "s", "XXX").replaceAll(" ", "0")


        It will fill your String XXX up to 9 Chars with a whitespace. After that all Whitespaces will be replaced with a 0. You can change the whitespace and the 0 to whatever you want...






        share|improve this answer































          2














          public static String padLeft(String in, int size, char padChar) {                
          if (in.length() <= size) {
          char temp = new char[size];
          /* Llenado Array con el padChar*/
          for(int i =0;i<size;i++){
          temp[i]= padChar;
          }
          int posIniTemp = size-in.length();
          for(int i=0;i<in.length();i++){
          temp[posIniTemp]=in.charAt(i);
          posIniTemp++;
          }
          return new String(temp);
          }
          return "";
          }





          share|improve this answer































            2














            Let's me leave an answer for some cases that you need to give left/right padding (or prefix/suffix string or spaces) before you concatenate to another string and you don't want to test length or any if condition.



            The same to the selected answer, I would prefer the StringUtils of Apache Commons but using this way:



            StringUtils.defaultString(StringUtils.leftPad(myString, 1))


            Explain:





            • myString: the string I input, can be null


            • StringUtils.leftPad(myString, 1): if string is null, this statement would return null too

            • then use defaultString to give empty string to prevent concatenate null






            share|improve this answer

































              2














              Found this on Dzone



              Pad with zeros:



              String.format("|%020d|", 93); // prints: |00000000000000000093|





              share|improve this answer
























              • This should be the answer, simple and concise, no need to install external libraries.

                – Wong Jia Hau
                Aug 27 '18 at 4:10



















              1














              java.util.Formatter will do left and right padding. No need for odd third party dependencies (would you want to add them for something so trivial).



              [I've left out the details and made this post 'community wiki' as it is not something I have a need for.]






              share|improve this answer





















              • 4





                I disagree. In any larger Java project you will typically do such a lot of String manipulation, that the increased readability and avoidance of errors is well worth using Apache Commons Lang. You all know code like someString.subString(someString.indexOf(startCharacter), someString.lastIndexOf(endCharacter)), which can easily be avoided with StringUtils.

                – Bananeweizen
                May 30 '11 at 20:15



















              1














              @ck's and @Marlon Tarak's answers are the only ones to use a char, which for applications that have several calls to padding methods per second is the best approach. However, they don't take advantage of any array manipulation optimizations and are a little overwritten for my taste; this can be done with no loops at all.



              public static String pad(String source, char fill, int length, boolean right){
              if(source.length() > length) return source;
              char out = new char[length];
              if(right){
              System.arraycopy(source.toCharArray(), 0, out, 0, source.length());
              Arrays.fill(out, source.length(), length, fill);
              }else{
              int sourceOffset = length - source.length();
              System.arraycopy(source.toCharArray(), 0, out, sourceOffset, source.length());
              Arrays.fill(out, 0, sourceOffset, fill);
              }
              return new String(out);
              }


              Simple test method:



              public static void main(String... args){
              System.out.println("012345678901234567890123456789");
              System.out.println(pad("cats", ' ', 30, true));
              System.out.println(pad("cats", ' ', 30, false));
              System.out.println(pad("cats", ' ', 20, false));
              System.out.println(pad("cats", '$', 30, true));
              System.out.println(pad("too long for your own good, buddy", '#', 30, true));
              }


              Outputs:



              012345678901234567890123456789
              cats
              cats
              cats
              cats$$$$$$$$$$$$$$$$$$$$$$$$$$
              too long for your own good, buddy





              share|improve this answer

































                1














                Use this function.



                private String leftPadding(String word, int length, char ch) {
                return (length > word.length()) ? leftPadding(ch + word, length, ch) : word;
                }


                how to use?



                leftPadding(month, 2, '0');


                output:
                01 02 03 04 .. 11 12






                share|improve this answer

































                  1














                  A lot of people have some very interesting techniques but I like to keep it simple so I go with this :



                  public static String padRight(String s, int n, char padding){
                  StringBuilder builder = new StringBuilder(s.length() + n);
                  builder.append(s);
                  for(int i = 0; i < n; i++){
                  builder.append(padding);
                  }
                  return builder.toString();
                  }

                  public static String padLeft(String s, int n, char padding) {
                  StringBuilder builder = new StringBuilder(s.length() + n);
                  for(int i = 0; i < n; i++){
                  builder.append(Character.toString(padding));
                  }
                  return builder.append(s).toString();
                  }

                  public static String pad(String s, int n, char padding){
                  StringBuilder pad = new StringBuilder(s.length() + n * 2);
                  StringBuilder value = new StringBuilder(n);
                  for(int i = 0; i < n; i++){
                  pad.append(padding);
                  }
                  return value.append(pad).append(s).append(pad).toString();
                  }





                  share|improve this answer





















                  • 2





                    This is very inefficient, you should use a StringBuilder

                    – wkarl
                    Feb 25 '16 at 10:23











                  • Since you already know the length, you should tell the StringBuilder to allocate that much space when you instantiate it.

                    – Ariel
                    Jun 15 '18 at 0:28











                  • @Ariel interesting that you mention that because I was just talking to someone else about that today lol.

                    – Aelphaeis
                    Jun 15 '18 at 19:05





















                  0














                  A simple solution without any API will be as follows:



                  public String pad(String num, int len){
                  if(len-num.length() <=0) return num;
                  StringBuffer sb = new StringBuffer();
                  for(i=0; i<(len-num.length()); i++){
                  sb.append("0");
                  }
                  sb.append(num);
                  return sb.toString();
                  }





                  share|improve this answer

































                    0














                    Java oneliners, no fancy library.



                    // 6 characters padding example
                    String pad = "******";
                    // testcases for 0, 4, 8 characters
                    String input = "" | "abcd" | "abcdefgh"


                    Pad Left, don't limit



                    result = pad.substring(Math.min(input.length(),pad.length())) + input;
                    results: "******" | "**abcd" | "abcdefgh"


                    Pad Right, don't limit



                    result = input + pad.substring(Math.min(input.length(),pad.length()));
                    results: "******" | "abcd**" | "abcdefgh"


                    Pad Left, limit to pad length



                    result = (pad + input).substring(input.length(), input.length() + pad.length());
                    results: "******" | "**abcd" | "cdefgh"


                    Pad Right, limit to pad length



                    result = (input + pad).substring(0, pad.length());
                    results: "******" | "abcd**" | "abcdef"





                    share|improve this answer































                      0














                      All string operation usually needs to be very efficient - especially if you are working with big sets of data. I wanted something that's fast and flexible, similar to what you will get in plsql pad command. Also, I don't want to include a huge lib for just one small thing. With these considerations none of these solutions were satisfactory. This is the solutions I came up with, that had the best bench-marking results, if anybody can improve on it, please add your comment.



                      public static char lpad(char pStringChar, int pTotalLength, char pPad) {
                      if (pStringChar.length < pTotalLength) {
                      char retChar = new char[pTotalLength];
                      int padIdx = pTotalLength - pStringChar.length;
                      Arrays.fill(retChar, 0, padIdx, pPad);
                      System.arraycopy(pStringChar, 0, retChar, padIdx, pStringChar.length);
                      return retChar;
                      } else {
                      return pStringChar;
                      }
                      }



                      • note it is called with String.toCharArray() and the result can be converted to String with new String((char)result). The reason for this is, if you applying multiple operations you can do them all on char and not keep on converting between formats - behind the scenes, String is stored as char. If these operations were included in the String class itself, it would have been twice as efficient - speed and memory wise.






                      share|improve this answer































                        0














                        Since Java 11, String.repeat(int) can be used to left/right pad a given string.



                        System.out.println("*".repeat(5)+"apple");
                        System.out.println("apple"+"*".repeat(5));


                        Output:



                        *****apple
                        apple*****





                        share|improve this answer































                          -1














                          A simple solution would be:



                          package nl;
                          public class Padder {
                          public static void main(String args) {
                          String s = "123" ;
                          System.out.println("#"+(" " + s).substring(s.length())+"#");
                          }
                          }





                          share|improve this answer































                            -2














                            How is this



                            String is "hello" and required padding is 15 with "0" left pad



                            String ax="Hello";
                            while(ax.length() < 15) ax="0"+ax;





                            share|improve this answer
























                            • I liked this one. :)

                              – null
                              Mar 28 '14 at 7:37






                            • 8





                              this one generates up to 15 new strings.

                              – claj
                              Apr 14 '14 at 8:54











                            • @claj Yes, but this.

                              – ruffin
                              Nov 15 '16 at 3:23











                            Your Answer






                            StackExchange.ifUsing("editor", function () {
                            StackExchange.using("externalEditor", function () {
                            StackExchange.using("snippets", function () {
                            StackExchange.snippets.init();
                            });
                            });
                            }, "code-snippets");

                            StackExchange.ready(function() {
                            var channelOptions = {
                            tags: "".split(" "),
                            id: "1"
                            };
                            initTagRenderer("".split(" "), "".split(" "), channelOptions);

                            StackExchange.using("externalEditor", function() {
                            // Have to fire editor after snippets, if snippets enabled
                            if (StackExchange.settings.snippets.snippetsEnabled) {
                            StackExchange.using("snippets", function() {
                            createEditor();
                            });
                            }
                            else {
                            createEditor();
                            }
                            });

                            function createEditor() {
                            StackExchange.prepareEditor({
                            heartbeatType: 'answer',
                            autoActivateHeartbeat: false,
                            convertImagesToLinks: true,
                            noModals: true,
                            showLowRepImageUploadWarning: true,
                            reputationToPostImages: 10,
                            bindNavPrevention: true,
                            postfix: "",
                            imageUploader: {
                            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                            allowUrls: true
                            },
                            onDemand: true,
                            discardSelector: ".discard-answer"
                            ,immediatelyShowMarkdownHelp:true
                            });


                            }
                            });














                            draft saved

                            draft discarded


















                            StackExchange.ready(
                            function () {
                            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f388461%2fhow-can-i-pad-a-string-in-java%23new-answer', 'question_page');
                            }
                            );

                            Post as a guest















                            Required, but never shown

























                            27 Answers
                            27






                            active

                            oldest

                            votes








                            27 Answers
                            27






                            active

                            oldest

                            votes









                            active

                            oldest

                            votes






                            active

                            oldest

                            votes









                            158














                            Apache StringUtils has several methods: leftPad, rightPad, center and repeat.



                            But please note that — as others have mentioned and demonstrated in this answer — String.format() and the Formatter classes in the JDK are better options. Use them over the commons code.






                            share|improve this answer





















                            • 79





                              java.util.Formatter (and String.format()) does this. Always prefer the JDK to an external library if the JDK version does the job (which it does).

                              – cletus
                              Dec 23 '08 at 12:02






                            • 6





                              For several reasons, I'd now prefer Guava to Apache Commons; this answer shows how to do it in Guava.

                              – Jonik
                              Oct 24 '12 at 12:37








                            • 1





                              @Jonik would you care to list some of your reasons? The APIs look pretty much the same.

                              – glen3b
                              May 18 '14 at 5:18






                            • 3





                              @glen3b: For an individual utility, like these string padding helpers, it really makes no difference which lib to use. That said, Guava is overall a more modern, cleaner and better documented lib than its counterparts in various Apache Commons projects (Commons Lang, Commons Collections, Commons IO, etc). It's also built by really smart guys (Kevin Bourrillion et al), many of whom are active at SO. Myself I ended up replacing the various Apache Commons libs with just Guava years ago, and have had no regrets.

                              – Jonik
                              May 18 '14 at 18:59








                            • 3





                              @glen3b: Some good further reading at this question.

                              – Jonik
                              May 18 '14 at 19:00


















                            158














                            Apache StringUtils has several methods: leftPad, rightPad, center and repeat.



                            But please note that — as others have mentioned and demonstrated in this answer — String.format() and the Formatter classes in the JDK are better options. Use them over the commons code.






                            share|improve this answer





















                            • 79





                              java.util.Formatter (and String.format()) does this. Always prefer the JDK to an external library if the JDK version does the job (which it does).

                              – cletus
                              Dec 23 '08 at 12:02






                            • 6





                              For several reasons, I'd now prefer Guava to Apache Commons; this answer shows how to do it in Guava.

                              – Jonik
                              Oct 24 '12 at 12:37








                            • 1





                              @Jonik would you care to list some of your reasons? The APIs look pretty much the same.

                              – glen3b
                              May 18 '14 at 5:18






                            • 3





                              @glen3b: For an individual utility, like these string padding helpers, it really makes no difference which lib to use. That said, Guava is overall a more modern, cleaner and better documented lib than its counterparts in various Apache Commons projects (Commons Lang, Commons Collections, Commons IO, etc). It's also built by really smart guys (Kevin Bourrillion et al), many of whom are active at SO. Myself I ended up replacing the various Apache Commons libs with just Guava years ago, and have had no regrets.

                              – Jonik
                              May 18 '14 at 18:59








                            • 3





                              @glen3b: Some good further reading at this question.

                              – Jonik
                              May 18 '14 at 19:00
















                            158












                            158








                            158







                            Apache StringUtils has several methods: leftPad, rightPad, center and repeat.



                            But please note that — as others have mentioned and demonstrated in this answer — String.format() and the Formatter classes in the JDK are better options. Use them over the commons code.






                            share|improve this answer















                            Apache StringUtils has several methods: leftPad, rightPad, center and repeat.



                            But please note that — as others have mentioned and demonstrated in this answer — String.format() and the Formatter classes in the JDK are better options. Use them over the commons code.







                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Jun 23 '18 at 22:09









                            Lonely Neuron

                            2,86831732




                            2,86831732










                            answered Dec 23 '08 at 9:22









                            GaryFGaryF

                            20.2k84969




                            20.2k84969








                            • 79





                              java.util.Formatter (and String.format()) does this. Always prefer the JDK to an external library if the JDK version does the job (which it does).

                              – cletus
                              Dec 23 '08 at 12:02






                            • 6





                              For several reasons, I'd now prefer Guava to Apache Commons; this answer shows how to do it in Guava.

                              – Jonik
                              Oct 24 '12 at 12:37








                            • 1





                              @Jonik would you care to list some of your reasons? The APIs look pretty much the same.

                              – glen3b
                              May 18 '14 at 5:18






                            • 3





                              @glen3b: For an individual utility, like these string padding helpers, it really makes no difference which lib to use. That said, Guava is overall a more modern, cleaner and better documented lib than its counterparts in various Apache Commons projects (Commons Lang, Commons Collections, Commons IO, etc). It's also built by really smart guys (Kevin Bourrillion et al), many of whom are active at SO. Myself I ended up replacing the various Apache Commons libs with just Guava years ago, and have had no regrets.

                              – Jonik
                              May 18 '14 at 18:59








                            • 3





                              @glen3b: Some good further reading at this question.

                              – Jonik
                              May 18 '14 at 19:00
















                            • 79





                              java.util.Formatter (and String.format()) does this. Always prefer the JDK to an external library if the JDK version does the job (which it does).

                              – cletus
                              Dec 23 '08 at 12:02






                            • 6





                              For several reasons, I'd now prefer Guava to Apache Commons; this answer shows how to do it in Guava.

                              – Jonik
                              Oct 24 '12 at 12:37








                            • 1





                              @Jonik would you care to list some of your reasons? The APIs look pretty much the same.

                              – glen3b
                              May 18 '14 at 5:18






                            • 3





                              @glen3b: For an individual utility, like these string padding helpers, it really makes no difference which lib to use. That said, Guava is overall a more modern, cleaner and better documented lib than its counterparts in various Apache Commons projects (Commons Lang, Commons Collections, Commons IO, etc). It's also built by really smart guys (Kevin Bourrillion et al), many of whom are active at SO. Myself I ended up replacing the various Apache Commons libs with just Guava years ago, and have had no regrets.

                              – Jonik
                              May 18 '14 at 18:59








                            • 3





                              @glen3b: Some good further reading at this question.

                              – Jonik
                              May 18 '14 at 19:00










                            79




                            79





                            java.util.Formatter (and String.format()) does this. Always prefer the JDK to an external library if the JDK version does the job (which it does).

                            – cletus
                            Dec 23 '08 at 12:02





                            java.util.Formatter (and String.format()) does this. Always prefer the JDK to an external library if the JDK version does the job (which it does).

                            – cletus
                            Dec 23 '08 at 12:02




                            6




                            6





                            For several reasons, I'd now prefer Guava to Apache Commons; this answer shows how to do it in Guava.

                            – Jonik
                            Oct 24 '12 at 12:37







                            For several reasons, I'd now prefer Guava to Apache Commons; this answer shows how to do it in Guava.

                            – Jonik
                            Oct 24 '12 at 12:37






                            1




                            1





                            @Jonik would you care to list some of your reasons? The APIs look pretty much the same.

                            – glen3b
                            May 18 '14 at 5:18





                            @Jonik would you care to list some of your reasons? The APIs look pretty much the same.

                            – glen3b
                            May 18 '14 at 5:18




                            3




                            3





                            @glen3b: For an individual utility, like these string padding helpers, it really makes no difference which lib to use. That said, Guava is overall a more modern, cleaner and better documented lib than its counterparts in various Apache Commons projects (Commons Lang, Commons Collections, Commons IO, etc). It's also built by really smart guys (Kevin Bourrillion et al), many of whom are active at SO. Myself I ended up replacing the various Apache Commons libs with just Guava years ago, and have had no regrets.

                            – Jonik
                            May 18 '14 at 18:59







                            @glen3b: For an individual utility, like these string padding helpers, it really makes no difference which lib to use. That said, Guava is overall a more modern, cleaner and better documented lib than its counterparts in various Apache Commons projects (Commons Lang, Commons Collections, Commons IO, etc). It's also built by really smart guys (Kevin Bourrillion et al), many of whom are active at SO. Myself I ended up replacing the various Apache Commons libs with just Guava years ago, and have had no regrets.

                            – Jonik
                            May 18 '14 at 18:59






                            3




                            3





                            @glen3b: Some good further reading at this question.

                            – Jonik
                            May 18 '14 at 19:00







                            @glen3b: Some good further reading at this question.

                            – Jonik
                            May 18 '14 at 19:00















                            566














                            Since Java 1.5, String.format() can be used to left/right pad a given string.



                            public static String padRight(String s, int n) {
                            return String.format("%-" + n + "s", s);
                            }

                            public static String padLeft(String s, int n) {
                            return String.format("%" + n + "s", s);
                            }

                            ...

                            public static void main(String args) throws Exception {
                            System.out.println(padRight("Howto", 20) + "*");
                            System.out.println(padLeft("Howto", 20) + "*");
                            }


                            And the output is:



                            Howto               *
                            Howto*





                            share|improve this answer





















                            • 33





                              What if you need to lpad with other chars (not spaces) ? Is it still possible with String.format ? I am not able to make it work...

                              – Guido
                              Aug 11 '09 at 15:48






                            • 6





                              AFAIK String.format() can't do that but it's not too difficult to code it, see rgagnon.com/javadetails/java-0448.html (2nd example)

                              – RealHowTo
                              Dec 7 '09 at 14:47






                            • 61





                              @Nullw0rm, if you're referring to rgagnon.com, be aware that RealHowTo is the author of rgagnon.com too, so he would be crediting himself...

                              – Colin Pickard
                              Nov 12 '10 at 14:17






                            • 3





                              at least on my JVM, the "#" doesn't work, the "-" is fine. (Just delete the #). This may be consistent with the formatter documentation, I dunno; it says "'#' 'u0023' Requires the output use an alternate form. The definition of the form is specified by the conversion."

                              – gatoatigrado
                              Jan 2 '11 at 21:25








                            • 6





                              Thanks for the awesome answer. I have a doubt though, what is the 1$ for? @leo has made a very similar answer that doesn't use 1$ and it apparently has the same effect. Does it make a difference?

                              – Fabrício Matté
                              Mar 8 '13 at 19:14


















                            566














                            Since Java 1.5, String.format() can be used to left/right pad a given string.



                            public static String padRight(String s, int n) {
                            return String.format("%-" + n + "s", s);
                            }

                            public static String padLeft(String s, int n) {
                            return String.format("%" + n + "s", s);
                            }

                            ...

                            public static void main(String args) throws Exception {
                            System.out.println(padRight("Howto", 20) + "*");
                            System.out.println(padLeft("Howto", 20) + "*");
                            }


                            And the output is:



                            Howto               *
                            Howto*





                            share|improve this answer





















                            • 33





                              What if you need to lpad with other chars (not spaces) ? Is it still possible with String.format ? I am not able to make it work...

                              – Guido
                              Aug 11 '09 at 15:48






                            • 6





                              AFAIK String.format() can't do that but it's not too difficult to code it, see rgagnon.com/javadetails/java-0448.html (2nd example)

                              – RealHowTo
                              Dec 7 '09 at 14:47






                            • 61





                              @Nullw0rm, if you're referring to rgagnon.com, be aware that RealHowTo is the author of rgagnon.com too, so he would be crediting himself...

                              – Colin Pickard
                              Nov 12 '10 at 14:17






                            • 3





                              at least on my JVM, the "#" doesn't work, the "-" is fine. (Just delete the #). This may be consistent with the formatter documentation, I dunno; it says "'#' 'u0023' Requires the output use an alternate form. The definition of the form is specified by the conversion."

                              – gatoatigrado
                              Jan 2 '11 at 21:25








                            • 6





                              Thanks for the awesome answer. I have a doubt though, what is the 1$ for? @leo has made a very similar answer that doesn't use 1$ and it apparently has the same effect. Does it make a difference?

                              – Fabrício Matté
                              Mar 8 '13 at 19:14
















                            566












                            566








                            566







                            Since Java 1.5, String.format() can be used to left/right pad a given string.



                            public static String padRight(String s, int n) {
                            return String.format("%-" + n + "s", s);
                            }

                            public static String padLeft(String s, int n) {
                            return String.format("%" + n + "s", s);
                            }

                            ...

                            public static void main(String args) throws Exception {
                            System.out.println(padRight("Howto", 20) + "*");
                            System.out.println(padLeft("Howto", 20) + "*");
                            }


                            And the output is:



                            Howto               *
                            Howto*





                            share|improve this answer















                            Since Java 1.5, String.format() can be used to left/right pad a given string.



                            public static String padRight(String s, int n) {
                            return String.format("%-" + n + "s", s);
                            }

                            public static String padLeft(String s, int n) {
                            return String.format("%" + n + "s", s);
                            }

                            ...

                            public static void main(String args) throws Exception {
                            System.out.println(padRight("Howto", 20) + "*");
                            System.out.println(padLeft("Howto", 20) + "*");
                            }


                            And the output is:



                            Howto               *
                            Howto*






                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Jan 26 at 1:05

























                            answered Dec 24 '08 at 18:21









                            RealHowToRealHowTo

                            27.9k96076




                            27.9k96076








                            • 33





                              What if you need to lpad with other chars (not spaces) ? Is it still possible with String.format ? I am not able to make it work...

                              – Guido
                              Aug 11 '09 at 15:48






                            • 6





                              AFAIK String.format() can't do that but it's not too difficult to code it, see rgagnon.com/javadetails/java-0448.html (2nd example)

                              – RealHowTo
                              Dec 7 '09 at 14:47






                            • 61





                              @Nullw0rm, if you're referring to rgagnon.com, be aware that RealHowTo is the author of rgagnon.com too, so he would be crediting himself...

                              – Colin Pickard
                              Nov 12 '10 at 14:17






                            • 3





                              at least on my JVM, the "#" doesn't work, the "-" is fine. (Just delete the #). This may be consistent with the formatter documentation, I dunno; it says "'#' 'u0023' Requires the output use an alternate form. The definition of the form is specified by the conversion."

                              – gatoatigrado
                              Jan 2 '11 at 21:25








                            • 6





                              Thanks for the awesome answer. I have a doubt though, what is the 1$ for? @leo has made a very similar answer that doesn't use 1$ and it apparently has the same effect. Does it make a difference?

                              – Fabrício Matté
                              Mar 8 '13 at 19:14
















                            • 33





                              What if you need to lpad with other chars (not spaces) ? Is it still possible with String.format ? I am not able to make it work...

                              – Guido
                              Aug 11 '09 at 15:48






                            • 6





                              AFAIK String.format() can't do that but it's not too difficult to code it, see rgagnon.com/javadetails/java-0448.html (2nd example)

                              – RealHowTo
                              Dec 7 '09 at 14:47






                            • 61





                              @Nullw0rm, if you're referring to rgagnon.com, be aware that RealHowTo is the author of rgagnon.com too, so he would be crediting himself...

                              – Colin Pickard
                              Nov 12 '10 at 14:17






                            • 3





                              at least on my JVM, the "#" doesn't work, the "-" is fine. (Just delete the #). This may be consistent with the formatter documentation, I dunno; it says "'#' 'u0023' Requires the output use an alternate form. The definition of the form is specified by the conversion."

                              – gatoatigrado
                              Jan 2 '11 at 21:25








                            • 6





                              Thanks for the awesome answer. I have a doubt though, what is the 1$ for? @leo has made a very similar answer that doesn't use 1$ and it apparently has the same effect. Does it make a difference?

                              – Fabrício Matté
                              Mar 8 '13 at 19:14










                            33




                            33





                            What if you need to lpad with other chars (not spaces) ? Is it still possible with String.format ? I am not able to make it work...

                            – Guido
                            Aug 11 '09 at 15:48





                            What if you need to lpad with other chars (not spaces) ? Is it still possible with String.format ? I am not able to make it work...

                            – Guido
                            Aug 11 '09 at 15:48




                            6




                            6





                            AFAIK String.format() can't do that but it's not too difficult to code it, see rgagnon.com/javadetails/java-0448.html (2nd example)

                            – RealHowTo
                            Dec 7 '09 at 14:47





                            AFAIK String.format() can't do that but it's not too difficult to code it, see rgagnon.com/javadetails/java-0448.html (2nd example)

                            – RealHowTo
                            Dec 7 '09 at 14:47




                            61




                            61





                            @Nullw0rm, if you're referring to rgagnon.com, be aware that RealHowTo is the author of rgagnon.com too, so he would be crediting himself...

                            – Colin Pickard
                            Nov 12 '10 at 14:17





                            @Nullw0rm, if you're referring to rgagnon.com, be aware that RealHowTo is the author of rgagnon.com too, so he would be crediting himself...

                            – Colin Pickard
                            Nov 12 '10 at 14:17




                            3




                            3





                            at least on my JVM, the "#" doesn't work, the "-" is fine. (Just delete the #). This may be consistent with the formatter documentation, I dunno; it says "'#' 'u0023' Requires the output use an alternate form. The definition of the form is specified by the conversion."

                            – gatoatigrado
                            Jan 2 '11 at 21:25







                            at least on my JVM, the "#" doesn't work, the "-" is fine. (Just delete the #). This may be consistent with the formatter documentation, I dunno; it says "'#' 'u0023' Requires the output use an alternate form. The definition of the form is specified by the conversion."

                            – gatoatigrado
                            Jan 2 '11 at 21:25






                            6




                            6





                            Thanks for the awesome answer. I have a doubt though, what is the 1$ for? @leo has made a very similar answer that doesn't use 1$ and it apparently has the same effect. Does it make a difference?

                            – Fabrício Matté
                            Mar 8 '13 at 19:14







                            Thanks for the awesome answer. I have a doubt though, what is the 1$ for? @leo has made a very similar answer that doesn't use 1$ and it apparently has the same effect. Does it make a difference?

                            – Fabrício Matté
                            Mar 8 '13 at 19:14













                            234














                            Padding to 10 characters:



                            String.format("%10s", "foo").replace(' ', '*');
                            String.format("%-10s", "bar").replace(' ', '*');
                            String.format("%10s", "longer than 10 chars").replace(' ', '*');


                            output:



                              *******foo
                            bar*******
                            longer*than*10*chars


                            Display '*' for characters of password:



                            String password = "secret123";
                            String padded = String.format("%"+password.length()+"s", "").replace(' ', '*');


                            output has the same length as the password string:



                              secret123
                            *********





                            share|improve this answer



















                            • 43





                              Just as long as we all remember not to pass in a string with spaces... :D

                              – aboveyou00
                              Jan 18 '13 at 3:20






                            • 4





                              I'm with @aboveyou00--this is a horrendous solution for strings with spaces, including the example provided by leo. A solution for padding a string on the left or the right should not alter the input string as it appears in the output, unless the input string's original padding causes it to exceed the specified padding length.

                              – Brian Warshaw
                              Jan 29 '15 at 16:24






                            • 2





                              Acknowledge the space issue. .replace(' ', '*') was rather intended to show the effect of padding. The password hiding expression does not have this issue anyway... For a better answer on customizing the left and right padding string using native Java feature see my other answer.

                              – leo
                              Aug 31 '17 at 21:12











                            • If the string contains only single spaces and you want to pad with different characters, you can use regex replace with look behind/ahead: String.format("%30s", "pad left").replaceAll("(?<=( |^)) ", "*") or String.format("%-30s", "pad right").replaceAll(" (?=( |$))", "*")

                              – Jaroslaw Pawlak
                              Jun 26 '18 at 11:01
















                            234














                            Padding to 10 characters:



                            String.format("%10s", "foo").replace(' ', '*');
                            String.format("%-10s", "bar").replace(' ', '*');
                            String.format("%10s", "longer than 10 chars").replace(' ', '*');


                            output:



                              *******foo
                            bar*******
                            longer*than*10*chars


                            Display '*' for characters of password:



                            String password = "secret123";
                            String padded = String.format("%"+password.length()+"s", "").replace(' ', '*');


                            output has the same length as the password string:



                              secret123
                            *********





                            share|improve this answer



















                            • 43





                              Just as long as we all remember not to pass in a string with spaces... :D

                              – aboveyou00
                              Jan 18 '13 at 3:20






                            • 4





                              I'm with @aboveyou00--this is a horrendous solution for strings with spaces, including the example provided by leo. A solution for padding a string on the left or the right should not alter the input string as it appears in the output, unless the input string's original padding causes it to exceed the specified padding length.

                              – Brian Warshaw
                              Jan 29 '15 at 16:24






                            • 2





                              Acknowledge the space issue. .replace(' ', '*') was rather intended to show the effect of padding. The password hiding expression does not have this issue anyway... For a better answer on customizing the left and right padding string using native Java feature see my other answer.

                              – leo
                              Aug 31 '17 at 21:12











                            • If the string contains only single spaces and you want to pad with different characters, you can use regex replace with look behind/ahead: String.format("%30s", "pad left").replaceAll("(?<=( |^)) ", "*") or String.format("%-30s", "pad right").replaceAll(" (?=( |$))", "*")

                              – Jaroslaw Pawlak
                              Jun 26 '18 at 11:01














                            234












                            234








                            234







                            Padding to 10 characters:



                            String.format("%10s", "foo").replace(' ', '*');
                            String.format("%-10s", "bar").replace(' ', '*');
                            String.format("%10s", "longer than 10 chars").replace(' ', '*');


                            output:



                              *******foo
                            bar*******
                            longer*than*10*chars


                            Display '*' for characters of password:



                            String password = "secret123";
                            String padded = String.format("%"+password.length()+"s", "").replace(' ', '*');


                            output has the same length as the password string:



                              secret123
                            *********





                            share|improve this answer













                            Padding to 10 characters:



                            String.format("%10s", "foo").replace(' ', '*');
                            String.format("%-10s", "bar").replace(' ', '*');
                            String.format("%10s", "longer than 10 chars").replace(' ', '*');


                            output:



                              *******foo
                            bar*******
                            longer*than*10*chars


                            Display '*' for characters of password:



                            String password = "secret123";
                            String padded = String.format("%"+password.length()+"s", "").replace(' ', '*');


                            output has the same length as the password string:



                              secret123
                            *********






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered May 31 '11 at 9:13









                            leoleo

                            2,58721415




                            2,58721415








                            • 43





                              Just as long as we all remember not to pass in a string with spaces... :D

                              – aboveyou00
                              Jan 18 '13 at 3:20






                            • 4





                              I'm with @aboveyou00--this is a horrendous solution for strings with spaces, including the example provided by leo. A solution for padding a string on the left or the right should not alter the input string as it appears in the output, unless the input string's original padding causes it to exceed the specified padding length.

                              – Brian Warshaw
                              Jan 29 '15 at 16:24






                            • 2





                              Acknowledge the space issue. .replace(' ', '*') was rather intended to show the effect of padding. The password hiding expression does not have this issue anyway... For a better answer on customizing the left and right padding string using native Java feature see my other answer.

                              – leo
                              Aug 31 '17 at 21:12











                            • If the string contains only single spaces and you want to pad with different characters, you can use regex replace with look behind/ahead: String.format("%30s", "pad left").replaceAll("(?<=( |^)) ", "*") or String.format("%-30s", "pad right").replaceAll(" (?=( |$))", "*")

                              – Jaroslaw Pawlak
                              Jun 26 '18 at 11:01














                            • 43





                              Just as long as we all remember not to pass in a string with spaces... :D

                              – aboveyou00
                              Jan 18 '13 at 3:20






                            • 4





                              I'm with @aboveyou00--this is a horrendous solution for strings with spaces, including the example provided by leo. A solution for padding a string on the left or the right should not alter the input string as it appears in the output, unless the input string's original padding causes it to exceed the specified padding length.

                              – Brian Warshaw
                              Jan 29 '15 at 16:24






                            • 2





                              Acknowledge the space issue. .replace(' ', '*') was rather intended to show the effect of padding. The password hiding expression does not have this issue anyway... For a better answer on customizing the left and right padding string using native Java feature see my other answer.

                              – leo
                              Aug 31 '17 at 21:12











                            • If the string contains only single spaces and you want to pad with different characters, you can use regex replace with look behind/ahead: String.format("%30s", "pad left").replaceAll("(?<=( |^)) ", "*") or String.format("%-30s", "pad right").replaceAll(" (?=( |$))", "*")

                              – Jaroslaw Pawlak
                              Jun 26 '18 at 11:01








                            43




                            43





                            Just as long as we all remember not to pass in a string with spaces... :D

                            – aboveyou00
                            Jan 18 '13 at 3:20





                            Just as long as we all remember not to pass in a string with spaces... :D

                            – aboveyou00
                            Jan 18 '13 at 3:20




                            4




                            4





                            I'm with @aboveyou00--this is a horrendous solution for strings with spaces, including the example provided by leo. A solution for padding a string on the left or the right should not alter the input string as it appears in the output, unless the input string's original padding causes it to exceed the specified padding length.

                            – Brian Warshaw
                            Jan 29 '15 at 16:24





                            I'm with @aboveyou00--this is a horrendous solution for strings with spaces, including the example provided by leo. A solution for padding a string on the left or the right should not alter the input string as it appears in the output, unless the input string's original padding causes it to exceed the specified padding length.

                            – Brian Warshaw
                            Jan 29 '15 at 16:24




                            2




                            2





                            Acknowledge the space issue. .replace(' ', '*') was rather intended to show the effect of padding. The password hiding expression does not have this issue anyway... For a better answer on customizing the left and right padding string using native Java feature see my other answer.

                            – leo
                            Aug 31 '17 at 21:12





                            Acknowledge the space issue. .replace(' ', '*') was rather intended to show the effect of padding. The password hiding expression does not have this issue anyway... For a better answer on customizing the left and right padding string using native Java feature see my other answer.

                            – leo
                            Aug 31 '17 at 21:12













                            If the string contains only single spaces and you want to pad with different characters, you can use regex replace with look behind/ahead: String.format("%30s", "pad left").replaceAll("(?<=( |^)) ", "*") or String.format("%-30s", "pad right").replaceAll(" (?=( |$))", "*")

                            – Jaroslaw Pawlak
                            Jun 26 '18 at 11:01





                            If the string contains only single spaces and you want to pad with different characters, you can use regex replace with look behind/ahead: String.format("%30s", "pad left").replaceAll("(?<=( |^)) ", "*") or String.format("%-30s", "pad right").replaceAll(" (?=( |$))", "*")

                            – Jaroslaw Pawlak
                            Jun 26 '18 at 11:01











                            86














                            In Guava, this is easy:



                            Strings.padStart("string", 10, ' ');
                            Strings.padEnd("string", 10, ' ');





                            share|improve this answer



















                            • 9





                              +1. In any sensible modern Java project, this is the correct solution. :-)

                              – Jonik
                              Oct 24 '12 at 12:34






                            • 4





                              My java assignment is not sensible then

                              – Ben Winding
                              Aug 29 '18 at 14:43
















                            86














                            In Guava, this is easy:



                            Strings.padStart("string", 10, ' ');
                            Strings.padEnd("string", 10, ' ');





                            share|improve this answer



















                            • 9





                              +1. In any sensible modern Java project, this is the correct solution. :-)

                              – Jonik
                              Oct 24 '12 at 12:34






                            • 4





                              My java assignment is not sensible then

                              – Ben Winding
                              Aug 29 '18 at 14:43














                            86












                            86








                            86







                            In Guava, this is easy:



                            Strings.padStart("string", 10, ' ');
                            Strings.padEnd("string", 10, ' ');





                            share|improve this answer













                            In Guava, this is easy:



                            Strings.padStart("string", 10, ' ');
                            Strings.padEnd("string", 10, ' ');






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Sep 21 '11 at 15:56









                            Garrett HallGarrett Hall

                            23.6k105069




                            23.6k105069








                            • 9





                              +1. In any sensible modern Java project, this is the correct solution. :-)

                              – Jonik
                              Oct 24 '12 at 12:34






                            • 4





                              My java assignment is not sensible then

                              – Ben Winding
                              Aug 29 '18 at 14:43














                            • 9





                              +1. In any sensible modern Java project, this is the correct solution. :-)

                              – Jonik
                              Oct 24 '12 at 12:34






                            • 4





                              My java assignment is not sensible then

                              – Ben Winding
                              Aug 29 '18 at 14:43








                            9




                            9





                            +1. In any sensible modern Java project, this is the correct solution. :-)

                            – Jonik
                            Oct 24 '12 at 12:34





                            +1. In any sensible modern Java project, this is the correct solution. :-)

                            – Jonik
                            Oct 24 '12 at 12:34




                            4




                            4





                            My java assignment is not sensible then

                            – Ben Winding
                            Aug 29 '18 at 14:43





                            My java assignment is not sensible then

                            – Ben Winding
                            Aug 29 '18 at 14:43











                            29














                            Something simple:



                            The value should be a string. convert it to string, if it's not. Like "" + 123 or Integer.toString(123)



                            // let's assume value holds the String we want to pad
                            String value = "123";


                            Substring start from the value length char index until end length of padded:



                            String padded="00000000".substring(value.length()) + value;

                            // now padded is "00000123"


                            More precise



                            pad right:



                            String padded = value + ("ABCDEFGH".substring(value.length())); 

                            // now padded is "123DEFGH"


                            pad left:



                            String padString = "ABCDEFGH";
                            String padded = (padString.substring(0, padString.length() - value.length())) + value;

                            // now padded is "ABCDE123"





                            share|improve this answer





















                            • 3





                              Simple answer made over confusable. Atleast use 2 different variables names. I bet, you missed few upvotes, because people couldn't digest this quickly...

                              – mtk
                              Oct 17 '14 at 7:27











                            • thanks, i have updated to a more explained version.

                              – Shimon Doodkin
                              Oct 17 '14 at 8:58











                            • m02ph3u5 - thank you for editing

                              – Shimon Doodkin
                              Jun 4 '16 at 11:07
















                            29














                            Something simple:



                            The value should be a string. convert it to string, if it's not. Like "" + 123 or Integer.toString(123)



                            // let's assume value holds the String we want to pad
                            String value = "123";


                            Substring start from the value length char index until end length of padded:



                            String padded="00000000".substring(value.length()) + value;

                            // now padded is "00000123"


                            More precise



                            pad right:



                            String padded = value + ("ABCDEFGH".substring(value.length())); 

                            // now padded is "123DEFGH"


                            pad left:



                            String padString = "ABCDEFGH";
                            String padded = (padString.substring(0, padString.length() - value.length())) + value;

                            // now padded is "ABCDE123"





                            share|improve this answer





















                            • 3





                              Simple answer made over confusable. Atleast use 2 different variables names. I bet, you missed few upvotes, because people couldn't digest this quickly...

                              – mtk
                              Oct 17 '14 at 7:27











                            • thanks, i have updated to a more explained version.

                              – Shimon Doodkin
                              Oct 17 '14 at 8:58











                            • m02ph3u5 - thank you for editing

                              – Shimon Doodkin
                              Jun 4 '16 at 11:07














                            29












                            29








                            29







                            Something simple:



                            The value should be a string. convert it to string, if it's not. Like "" + 123 or Integer.toString(123)



                            // let's assume value holds the String we want to pad
                            String value = "123";


                            Substring start from the value length char index until end length of padded:



                            String padded="00000000".substring(value.length()) + value;

                            // now padded is "00000123"


                            More precise



                            pad right:



                            String padded = value + ("ABCDEFGH".substring(value.length())); 

                            // now padded is "123DEFGH"


                            pad left:



                            String padString = "ABCDEFGH";
                            String padded = (padString.substring(0, padString.length() - value.length())) + value;

                            // now padded is "ABCDE123"





                            share|improve this answer















                            Something simple:



                            The value should be a string. convert it to string, if it's not. Like "" + 123 or Integer.toString(123)



                            // let's assume value holds the String we want to pad
                            String value = "123";


                            Substring start from the value length char index until end length of padded:



                            String padded="00000000".substring(value.length()) + value;

                            // now padded is "00000123"


                            More precise



                            pad right:



                            String padded = value + ("ABCDEFGH".substring(value.length())); 

                            // now padded is "123DEFGH"


                            pad left:



                            String padString = "ABCDEFGH";
                            String padded = (padString.substring(0, padString.length() - value.length())) + value;

                            // now padded is "ABCDE123"






                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Jun 2 '16 at 13:44









                            m02ph3u5

                            1,86822234




                            1,86822234










                            answered Sep 2 '13 at 8:29









                            Shimon DoodkinShimon Doodkin

                            2,6742525




                            2,6742525








                            • 3





                              Simple answer made over confusable. Atleast use 2 different variables names. I bet, you missed few upvotes, because people couldn't digest this quickly...

                              – mtk
                              Oct 17 '14 at 7:27











                            • thanks, i have updated to a more explained version.

                              – Shimon Doodkin
                              Oct 17 '14 at 8:58











                            • m02ph3u5 - thank you for editing

                              – Shimon Doodkin
                              Jun 4 '16 at 11:07














                            • 3





                              Simple answer made over confusable. Atleast use 2 different variables names. I bet, you missed few upvotes, because people couldn't digest this quickly...

                              – mtk
                              Oct 17 '14 at 7:27











                            • thanks, i have updated to a more explained version.

                              – Shimon Doodkin
                              Oct 17 '14 at 8:58











                            • m02ph3u5 - thank you for editing

                              – Shimon Doodkin
                              Jun 4 '16 at 11:07








                            3




                            3





                            Simple answer made over confusable. Atleast use 2 different variables names. I bet, you missed few upvotes, because people couldn't digest this quickly...

                            – mtk
                            Oct 17 '14 at 7:27





                            Simple answer made over confusable. Atleast use 2 different variables names. I bet, you missed few upvotes, because people couldn't digest this quickly...

                            – mtk
                            Oct 17 '14 at 7:27













                            thanks, i have updated to a more explained version.

                            – Shimon Doodkin
                            Oct 17 '14 at 8:58





                            thanks, i have updated to a more explained version.

                            – Shimon Doodkin
                            Oct 17 '14 at 8:58













                            m02ph3u5 - thank you for editing

                            – Shimon Doodkin
                            Jun 4 '16 at 11:07





                            m02ph3u5 - thank you for editing

                            – Shimon Doodkin
                            Jun 4 '16 at 11:07











                            22














                            Have a look at org.apache.commons.lang.StringUtils#rightPad(String str, int size, char padChar).



                            But the algorithm is very simple (pad right up to size chars):



                            public String pad(String str, int size, char padChar)
                            {
                            StringBuffer padded = new StringBuffer(str);
                            while (padded.length() < size)
                            {
                            padded.append(padChar);
                            }
                            return padded.toString();
                            }





                            share|improve this answer



















                            • 11





                              Note that as of Java 1.5 it's worth using StringBuilder instead of StringBuffer.

                              – Jon Skeet
                              Dec 23 '08 at 9:34






                            • 1





                              You are right, it would be better to use if Java 5 is set.

                              – Arne Burmeister
                              Dec 23 '08 at 22:00
















                            22














                            Have a look at org.apache.commons.lang.StringUtils#rightPad(String str, int size, char padChar).



                            But the algorithm is very simple (pad right up to size chars):



                            public String pad(String str, int size, char padChar)
                            {
                            StringBuffer padded = new StringBuffer(str);
                            while (padded.length() < size)
                            {
                            padded.append(padChar);
                            }
                            return padded.toString();
                            }





                            share|improve this answer



















                            • 11





                              Note that as of Java 1.5 it's worth using StringBuilder instead of StringBuffer.

                              – Jon Skeet
                              Dec 23 '08 at 9:34






                            • 1





                              You are right, it would be better to use if Java 5 is set.

                              – Arne Burmeister
                              Dec 23 '08 at 22:00














                            22












                            22








                            22







                            Have a look at org.apache.commons.lang.StringUtils#rightPad(String str, int size, char padChar).



                            But the algorithm is very simple (pad right up to size chars):



                            public String pad(String str, int size, char padChar)
                            {
                            StringBuffer padded = new StringBuffer(str);
                            while (padded.length() < size)
                            {
                            padded.append(padChar);
                            }
                            return padded.toString();
                            }





                            share|improve this answer













                            Have a look at org.apache.commons.lang.StringUtils#rightPad(String str, int size, char padChar).



                            But the algorithm is very simple (pad right up to size chars):



                            public String pad(String str, int size, char padChar)
                            {
                            StringBuffer padded = new StringBuffer(str);
                            while (padded.length() < size)
                            {
                            padded.append(padChar);
                            }
                            return padded.toString();
                            }






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Dec 23 '08 at 9:24









                            Arne BurmeisterArne Burmeister

                            15k54277




                            15k54277








                            • 11





                              Note that as of Java 1.5 it's worth using StringBuilder instead of StringBuffer.

                              – Jon Skeet
                              Dec 23 '08 at 9:34






                            • 1





                              You are right, it would be better to use if Java 5 is set.

                              – Arne Burmeister
                              Dec 23 '08 at 22:00














                            • 11





                              Note that as of Java 1.5 it's worth using StringBuilder instead of StringBuffer.

                              – Jon Skeet
                              Dec 23 '08 at 9:34






                            • 1





                              You are right, it would be better to use if Java 5 is set.

                              – Arne Burmeister
                              Dec 23 '08 at 22:00








                            11




                            11





                            Note that as of Java 1.5 it's worth using StringBuilder instead of StringBuffer.

                            – Jon Skeet
                            Dec 23 '08 at 9:34





                            Note that as of Java 1.5 it's worth using StringBuilder instead of StringBuffer.

                            – Jon Skeet
                            Dec 23 '08 at 9:34




                            1




                            1





                            You are right, it would be better to use if Java 5 is set.

                            – Arne Burmeister
                            Dec 23 '08 at 22:00





                            You are right, it would be better to use if Java 5 is set.

                            – Arne Burmeister
                            Dec 23 '08 at 22:00











                            21














                            Besides Apache Commons, also see String.format which should be able to take care of simple padding (e.g. with spaces).






                            share|improve this answer




























                              21














                              Besides Apache Commons, also see String.format which should be able to take care of simple padding (e.g. with spaces).






                              share|improve this answer


























                                21












                                21








                                21







                                Besides Apache Commons, also see String.format which should be able to take care of simple padding (e.g. with spaces).






                                share|improve this answer













                                Besides Apache Commons, also see String.format which should be able to take care of simple padding (e.g. with spaces).







                                share|improve this answer












                                share|improve this answer



                                share|improve this answer










                                answered Dec 23 '08 at 9:24









                                Miserable VariableMiserable Variable

                                23.5k1155107




                                23.5k1155107























                                    16














                                    public static String LPad(String str, Integer length, char car) {
                                    return (str + String.format("%" + length + "s", "").replace(" ", String.valueOf(car))).substring(0, length);
                                    }

                                    public static String RPad(String str, Integer length, char car) {
                                    return (String.format("%" + length + "s", "").replace(" ", String.valueOf(car)) + str).substring(str.length(), length + str.length());
                                    }

                                    LPad("Hi", 10, 'R') //gives "RRRRRRRRHi"
                                    RPad("Hi", 10, 'R') //gives "HiRRRRRRRR"
                                    RPad("Hi", 10, ' ') //gives "Hi "
                                    RPad("Hi", 1, ' ') //gives "H"
                                    //etc...





                                    share|improve this answer





















                                    • 4





                                      Pay attention: you inverted functions names; if you run it you'll see.

                                      – bluish
                                      Feb 10 '12 at 7:52











                                    • plus if the original str contains spaces then this doesn't work

                                      – Steven Shaw
                                      Sep 27 '12 at 8:34











                                    • @StevenShaw If I'm not mistaken, the replace does not target the original str, so this is correct.

                                      – mafu
                                      Jun 22 '14 at 23:08






                                    • 3





                                      By convention you should not use a capital letter for function names.

                                      – principal-ideal-domain
                                      Aug 20 '14 at 12:04











                                    • Is there a missing conditional on returning the string as is when (length - str.length()) is 0? The formatter throws a FormatFlagsConversionMismatchException when %0s is the format string.

                                      – Devin Walters
                                      Jun 8 '18 at 17:16
















                                    16














                                    public static String LPad(String str, Integer length, char car) {
                                    return (str + String.format("%" + length + "s", "").replace(" ", String.valueOf(car))).substring(0, length);
                                    }

                                    public static String RPad(String str, Integer length, char car) {
                                    return (String.format("%" + length + "s", "").replace(" ", String.valueOf(car)) + str).substring(str.length(), length + str.length());
                                    }

                                    LPad("Hi", 10, 'R') //gives "RRRRRRRRHi"
                                    RPad("Hi", 10, 'R') //gives "HiRRRRRRRR"
                                    RPad("Hi", 10, ' ') //gives "Hi "
                                    RPad("Hi", 1, ' ') //gives "H"
                                    //etc...





                                    share|improve this answer





















                                    • 4





                                      Pay attention: you inverted functions names; if you run it you'll see.

                                      – bluish
                                      Feb 10 '12 at 7:52











                                    • plus if the original str contains spaces then this doesn't work

                                      – Steven Shaw
                                      Sep 27 '12 at 8:34











                                    • @StevenShaw If I'm not mistaken, the replace does not target the original str, so this is correct.

                                      – mafu
                                      Jun 22 '14 at 23:08






                                    • 3





                                      By convention you should not use a capital letter for function names.

                                      – principal-ideal-domain
                                      Aug 20 '14 at 12:04











                                    • Is there a missing conditional on returning the string as is when (length - str.length()) is 0? The formatter throws a FormatFlagsConversionMismatchException when %0s is the format string.

                                      – Devin Walters
                                      Jun 8 '18 at 17:16














                                    16












                                    16








                                    16







                                    public static String LPad(String str, Integer length, char car) {
                                    return (str + String.format("%" + length + "s", "").replace(" ", String.valueOf(car))).substring(0, length);
                                    }

                                    public static String RPad(String str, Integer length, char car) {
                                    return (String.format("%" + length + "s", "").replace(" ", String.valueOf(car)) + str).substring(str.length(), length + str.length());
                                    }

                                    LPad("Hi", 10, 'R') //gives "RRRRRRRRHi"
                                    RPad("Hi", 10, 'R') //gives "HiRRRRRRRR"
                                    RPad("Hi", 10, ' ') //gives "Hi "
                                    RPad("Hi", 1, ' ') //gives "H"
                                    //etc...





                                    share|improve this answer















                                    public static String LPad(String str, Integer length, char car) {
                                    return (str + String.format("%" + length + "s", "").replace(" ", String.valueOf(car))).substring(0, length);
                                    }

                                    public static String RPad(String str, Integer length, char car) {
                                    return (String.format("%" + length + "s", "").replace(" ", String.valueOf(car)) + str).substring(str.length(), length + str.length());
                                    }

                                    LPad("Hi", 10, 'R') //gives "RRRRRRRRHi"
                                    RPad("Hi", 10, 'R') //gives "HiRRRRRRRR"
                                    RPad("Hi", 10, ' ') //gives "Hi "
                                    RPad("Hi", 1, ' ') //gives "H"
                                    //etc...






                                    share|improve this answer














                                    share|improve this answer



                                    share|improve this answer








                                    edited Oct 6 '18 at 14:43









                                    Claudio Torres

                                    32




                                    32










                                    answered Feb 9 '12 at 17:22









                                    EduardoEduardo

                                    16912




                                    16912








                                    • 4





                                      Pay attention: you inverted functions names; if you run it you'll see.

                                      – bluish
                                      Feb 10 '12 at 7:52











                                    • plus if the original str contains spaces then this doesn't work

                                      – Steven Shaw
                                      Sep 27 '12 at 8:34











                                    • @StevenShaw If I'm not mistaken, the replace does not target the original str, so this is correct.

                                      – mafu
                                      Jun 22 '14 at 23:08






                                    • 3





                                      By convention you should not use a capital letter for function names.

                                      – principal-ideal-domain
                                      Aug 20 '14 at 12:04











                                    • Is there a missing conditional on returning the string as is when (length - str.length()) is 0? The formatter throws a FormatFlagsConversionMismatchException when %0s is the format string.

                                      – Devin Walters
                                      Jun 8 '18 at 17:16














                                    • 4





                                      Pay attention: you inverted functions names; if you run it you'll see.

                                      – bluish
                                      Feb 10 '12 at 7:52











                                    • plus if the original str contains spaces then this doesn't work

                                      – Steven Shaw
                                      Sep 27 '12 at 8:34











                                    • @StevenShaw If I'm not mistaken, the replace does not target the original str, so this is correct.

                                      – mafu
                                      Jun 22 '14 at 23:08






                                    • 3





                                      By convention you should not use a capital letter for function names.

                                      – principal-ideal-domain
                                      Aug 20 '14 at 12:04











                                    • Is there a missing conditional on returning the string as is when (length - str.length()) is 0? The formatter throws a FormatFlagsConversionMismatchException when %0s is the format string.

                                      – Devin Walters
                                      Jun 8 '18 at 17:16








                                    4




                                    4





                                    Pay attention: you inverted functions names; if you run it you'll see.

                                    – bluish
                                    Feb 10 '12 at 7:52





                                    Pay attention: you inverted functions names; if you run it you'll see.

                                    – bluish
                                    Feb 10 '12 at 7:52













                                    plus if the original str contains spaces then this doesn't work

                                    – Steven Shaw
                                    Sep 27 '12 at 8:34





                                    plus if the original str contains spaces then this doesn't work

                                    – Steven Shaw
                                    Sep 27 '12 at 8:34













                                    @StevenShaw If I'm not mistaken, the replace does not target the original str, so this is correct.

                                    – mafu
                                    Jun 22 '14 at 23:08





                                    @StevenShaw If I'm not mistaken, the replace does not target the original str, so this is correct.

                                    – mafu
                                    Jun 22 '14 at 23:08




                                    3




                                    3





                                    By convention you should not use a capital letter for function names.

                                    – principal-ideal-domain
                                    Aug 20 '14 at 12:04





                                    By convention you should not use a capital letter for function names.

                                    – principal-ideal-domain
                                    Aug 20 '14 at 12:04













                                    Is there a missing conditional on returning the string as is when (length - str.length()) is 0? The formatter throws a FormatFlagsConversionMismatchException when %0s is the format string.

                                    – Devin Walters
                                    Jun 8 '18 at 17:16





                                    Is there a missing conditional on returning the string as is when (length - str.length()) is 0? The formatter throws a FormatFlagsConversionMismatchException when %0s is the format string.

                                    – Devin Walters
                                    Jun 8 '18 at 17:16











                                    7














                                    This took me a little while to figure out.
                                    The real key is to read that Formatter documentation.



                                    // Get your data from wherever.
                                    final byte data = getData();
                                    // Get the digest engine.
                                    final MessageDigest md5= MessageDigest.getInstance("MD5");
                                    // Send your data through it.
                                    md5.update(data);
                                    // Parse the data as a positive BigInteger.
                                    final BigInteger digest = new BigInteger(1,md5.digest());
                                    // Pad the digest with blanks, 32 wide.
                                    String hex = String.format(
                                    // See: http://download.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html
                                    // Format: %[argument_index$][flags][width]conversion
                                    // Conversion: 'x', 'X' integral The result is formatted as a hexadecimal integer
                                    "%1$32x",
                                    digest
                                    );
                                    // Replace the blank padding with 0s.
                                    hex = hex.replace(" ","0");
                                    System.out.println(hex);





                                    share|improve this answer
























                                    • Why make the end so complicated? You could have just done String hex = String.format("%032x", digest); and had the exact same results, just without a needless replace() and having to use the $ to access specific variables (there's only one, after all.)

                                      – ArtOfWarfare
                                      Oct 17 '12 at 17:37











                                    • @ArtOfWarfare fair point. Someone originally asked for padding hex values in another question, I saw that I had a link to the formatter documentation. It's complicated for completeness.

                                      – Nthalk
                                      Mar 4 '14 at 21:42
















                                    7














                                    This took me a little while to figure out.
                                    The real key is to read that Formatter documentation.



                                    // Get your data from wherever.
                                    final byte data = getData();
                                    // Get the digest engine.
                                    final MessageDigest md5= MessageDigest.getInstance("MD5");
                                    // Send your data through it.
                                    md5.update(data);
                                    // Parse the data as a positive BigInteger.
                                    final BigInteger digest = new BigInteger(1,md5.digest());
                                    // Pad the digest with blanks, 32 wide.
                                    String hex = String.format(
                                    // See: http://download.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html
                                    // Format: %[argument_index$][flags][width]conversion
                                    // Conversion: 'x', 'X' integral The result is formatted as a hexadecimal integer
                                    "%1$32x",
                                    digest
                                    );
                                    // Replace the blank padding with 0s.
                                    hex = hex.replace(" ","0");
                                    System.out.println(hex);





                                    share|improve this answer
























                                    • Why make the end so complicated? You could have just done String hex = String.format("%032x", digest); and had the exact same results, just without a needless replace() and having to use the $ to access specific variables (there's only one, after all.)

                                      – ArtOfWarfare
                                      Oct 17 '12 at 17:37











                                    • @ArtOfWarfare fair point. Someone originally asked for padding hex values in another question, I saw that I had a link to the formatter documentation. It's complicated for completeness.

                                      – Nthalk
                                      Mar 4 '14 at 21:42














                                    7












                                    7








                                    7







                                    This took me a little while to figure out.
                                    The real key is to read that Formatter documentation.



                                    // Get your data from wherever.
                                    final byte data = getData();
                                    // Get the digest engine.
                                    final MessageDigest md5= MessageDigest.getInstance("MD5");
                                    // Send your data through it.
                                    md5.update(data);
                                    // Parse the data as a positive BigInteger.
                                    final BigInteger digest = new BigInteger(1,md5.digest());
                                    // Pad the digest with blanks, 32 wide.
                                    String hex = String.format(
                                    // See: http://download.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html
                                    // Format: %[argument_index$][flags][width]conversion
                                    // Conversion: 'x', 'X' integral The result is formatted as a hexadecimal integer
                                    "%1$32x",
                                    digest
                                    );
                                    // Replace the blank padding with 0s.
                                    hex = hex.replace(" ","0");
                                    System.out.println(hex);





                                    share|improve this answer













                                    This took me a little while to figure out.
                                    The real key is to read that Formatter documentation.



                                    // Get your data from wherever.
                                    final byte data = getData();
                                    // Get the digest engine.
                                    final MessageDigest md5= MessageDigest.getInstance("MD5");
                                    // Send your data through it.
                                    md5.update(data);
                                    // Parse the data as a positive BigInteger.
                                    final BigInteger digest = new BigInteger(1,md5.digest());
                                    // Pad the digest with blanks, 32 wide.
                                    String hex = String.format(
                                    // See: http://download.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html
                                    // Format: %[argument_index$][flags][width]conversion
                                    // Conversion: 'x', 'X' integral The result is formatted as a hexadecimal integer
                                    "%1$32x",
                                    digest
                                    );
                                    // Replace the blank padding with 0s.
                                    hex = hex.replace(" ","0");
                                    System.out.println(hex);






                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered Oct 29 '10 at 20:58









                                    NthalkNthalk

                                    3,34712019




                                    3,34712019













                                    • Why make the end so complicated? You could have just done String hex = String.format("%032x", digest); and had the exact same results, just without a needless replace() and having to use the $ to access specific variables (there's only one, after all.)

                                      – ArtOfWarfare
                                      Oct 17 '12 at 17:37











                                    • @ArtOfWarfare fair point. Someone originally asked for padding hex values in another question, I saw that I had a link to the formatter documentation. It's complicated for completeness.

                                      – Nthalk
                                      Mar 4 '14 at 21:42



















                                    • Why make the end so complicated? You could have just done String hex = String.format("%032x", digest); and had the exact same results, just without a needless replace() and having to use the $ to access specific variables (there's only one, after all.)

                                      – ArtOfWarfare
                                      Oct 17 '12 at 17:37











                                    • @ArtOfWarfare fair point. Someone originally asked for padding hex values in another question, I saw that I had a link to the formatter documentation. It's complicated for completeness.

                                      – Nthalk
                                      Mar 4 '14 at 21:42

















                                    Why make the end so complicated? You could have just done String hex = String.format("%032x", digest); and had the exact same results, just without a needless replace() and having to use the $ to access specific variables (there's only one, after all.)

                                    – ArtOfWarfare
                                    Oct 17 '12 at 17:37





                                    Why make the end so complicated? You could have just done String hex = String.format("%032x", digest); and had the exact same results, just without a needless replace() and having to use the $ to access specific variables (there's only one, after all.)

                                    – ArtOfWarfare
                                    Oct 17 '12 at 17:37













                                    @ArtOfWarfare fair point. Someone originally asked for padding hex values in another question, I saw that I had a link to the formatter documentation. It's complicated for completeness.

                                    – Nthalk
                                    Mar 4 '14 at 21:42





                                    @ArtOfWarfare fair point. Someone originally asked for padding hex values in another question, I saw that I had a link to the formatter documentation. It's complicated for completeness.

                                    – Nthalk
                                    Mar 4 '14 at 21:42











                                    6














                                    i know this thread is kind of old and the original question was for an easy solution but if it's supposed to be really fast, you should use a char array.



                                    public static String pad(String str, int size, char padChar)
                                    {
                                    if (str.length() < size)
                                    {
                                    char temp = new char[size];
                                    int i = 0;

                                    while (i < str.length())
                                    {
                                    temp[i] = str.charAt(i);
                                    i++;
                                    }

                                    while (i < size)
                                    {
                                    temp[i] = padChar;
                                    i++;
                                    }

                                    str = new String(temp);
                                    }

                                    return str;
                                    }


                                    the formatter solution is not optimal. just building the format string creates 2 new strings.



                                    apache's solution can be improved by initializing the sb with the target size so replacing below



                                    StringBuffer padded = new StringBuffer(str); 


                                    with



                                    StringBuffer padded = new StringBuffer(pad); 
                                    padded.append(value);


                                    would prevent the sb's internal buffer from growing.






                                    share|improve this answer
























                                    • If the StringBuffer can't be accessed by multiple threads at once (which in this case is true), you should use a StringBuilder (in JDK1.5+) to avoid the overhead of synchronization.

                                      – glen3b
                                      May 20 '14 at 23:40
















                                    6














                                    i know this thread is kind of old and the original question was for an easy solution but if it's supposed to be really fast, you should use a char array.



                                    public static String pad(String str, int size, char padChar)
                                    {
                                    if (str.length() < size)
                                    {
                                    char temp = new char[size];
                                    int i = 0;

                                    while (i < str.length())
                                    {
                                    temp[i] = str.charAt(i);
                                    i++;
                                    }

                                    while (i < size)
                                    {
                                    temp[i] = padChar;
                                    i++;
                                    }

                                    str = new String(temp);
                                    }

                                    return str;
                                    }


                                    the formatter solution is not optimal. just building the format string creates 2 new strings.



                                    apache's solution can be improved by initializing the sb with the target size so replacing below



                                    StringBuffer padded = new StringBuffer(str); 


                                    with



                                    StringBuffer padded = new StringBuffer(pad); 
                                    padded.append(value);


                                    would prevent the sb's internal buffer from growing.






                                    share|improve this answer
























                                    • If the StringBuffer can't be accessed by multiple threads at once (which in this case is true), you should use a StringBuilder (in JDK1.5+) to avoid the overhead of synchronization.

                                      – glen3b
                                      May 20 '14 at 23:40














                                    6












                                    6








                                    6







                                    i know this thread is kind of old and the original question was for an easy solution but if it's supposed to be really fast, you should use a char array.



                                    public static String pad(String str, int size, char padChar)
                                    {
                                    if (str.length() < size)
                                    {
                                    char temp = new char[size];
                                    int i = 0;

                                    while (i < str.length())
                                    {
                                    temp[i] = str.charAt(i);
                                    i++;
                                    }

                                    while (i < size)
                                    {
                                    temp[i] = padChar;
                                    i++;
                                    }

                                    str = new String(temp);
                                    }

                                    return str;
                                    }


                                    the formatter solution is not optimal. just building the format string creates 2 new strings.



                                    apache's solution can be improved by initializing the sb with the target size so replacing below



                                    StringBuffer padded = new StringBuffer(str); 


                                    with



                                    StringBuffer padded = new StringBuffer(pad); 
                                    padded.append(value);


                                    would prevent the sb's internal buffer from growing.






                                    share|improve this answer













                                    i know this thread is kind of old and the original question was for an easy solution but if it's supposed to be really fast, you should use a char array.



                                    public static String pad(String str, int size, char padChar)
                                    {
                                    if (str.length() < size)
                                    {
                                    char temp = new char[size];
                                    int i = 0;

                                    while (i < str.length())
                                    {
                                    temp[i] = str.charAt(i);
                                    i++;
                                    }

                                    while (i < size)
                                    {
                                    temp[i] = padChar;
                                    i++;
                                    }

                                    str = new String(temp);
                                    }

                                    return str;
                                    }


                                    the formatter solution is not optimal. just building the format string creates 2 new strings.



                                    apache's solution can be improved by initializing the sb with the target size so replacing below



                                    StringBuffer padded = new StringBuffer(str); 


                                    with



                                    StringBuffer padded = new StringBuffer(pad); 
                                    padded.append(value);


                                    would prevent the sb's internal buffer from growing.







                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered Oct 28 '10 at 14:34









                                    ck.ck.

                                    6112




                                    6112













                                    • If the StringBuffer can't be accessed by multiple threads at once (which in this case is true), you should use a StringBuilder (in JDK1.5+) to avoid the overhead of synchronization.

                                      – glen3b
                                      May 20 '14 at 23:40



















                                    • If the StringBuffer can't be accessed by multiple threads at once (which in this case is true), you should use a StringBuilder (in JDK1.5+) to avoid the overhead of synchronization.

                                      – glen3b
                                      May 20 '14 at 23:40

















                                    If the StringBuffer can't be accessed by multiple threads at once (which in this case is true), you should use a StringBuilder (in JDK1.5+) to avoid the overhead of synchronization.

                                    – glen3b
                                    May 20 '14 at 23:40





                                    If the StringBuffer can't be accessed by multiple threads at once (which in this case is true), you should use a StringBuilder (in JDK1.5+) to avoid the overhead of synchronization.

                                    – glen3b
                                    May 20 '14 at 23:40











                                    5














                                    Here is another way to pad to the right:



                                    // put the number of spaces, or any character you like, in your paddedString

                                    String paddedString = "--------------------";

                                    String myStringToBePadded = "I like donuts";

                                    myStringToBePadded = myStringToBePadded + paddedString.substring(myStringToBePadded.length());

                                    //result:
                                    myStringToBePadded = "I like donuts-------";





                                    share|improve this answer






























                                      5














                                      Here is another way to pad to the right:



                                      // put the number of spaces, or any character you like, in your paddedString

                                      String paddedString = "--------------------";

                                      String myStringToBePadded = "I like donuts";

                                      myStringToBePadded = myStringToBePadded + paddedString.substring(myStringToBePadded.length());

                                      //result:
                                      myStringToBePadded = "I like donuts-------";





                                      share|improve this answer




























                                        5












                                        5








                                        5







                                        Here is another way to pad to the right:



                                        // put the number of spaces, or any character you like, in your paddedString

                                        String paddedString = "--------------------";

                                        String myStringToBePadded = "I like donuts";

                                        myStringToBePadded = myStringToBePadded + paddedString.substring(myStringToBePadded.length());

                                        //result:
                                        myStringToBePadded = "I like donuts-------";





                                        share|improve this answer















                                        Here is another way to pad to the right:



                                        // put the number of spaces, or any character you like, in your paddedString

                                        String paddedString = "--------------------";

                                        String myStringToBePadded = "I like donuts";

                                        myStringToBePadded = myStringToBePadded + paddedString.substring(myStringToBePadded.length());

                                        //result:
                                        myStringToBePadded = "I like donuts-------";






                                        share|improve this answer














                                        share|improve this answer



                                        share|improve this answer








                                        edited Sep 21 '11 at 17:40









                                        Jason Plank

                                        2,14442738




                                        2,14442738










                                        answered Sep 21 '11 at 15:45









                                        fawsha1fawsha1

                                        749810




                                        749810























                                            4














                                            You can reduce the per-call overhead by retaining the padding data, rather than rebuilding it every time:



                                            public class RightPadder {

                                            private int length;
                                            private String padding;

                                            public RightPadder(int length, String pad) {
                                            this.length = length;
                                            StringBuilder sb = new StringBuilder(pad);
                                            while (sb.length() < length) {
                                            sb.append(sb);
                                            }
                                            padding = sb.toString();
                                            }

                                            public String pad(String s) {
                                            return (s.length() < length ? s + padding : s).substring(0, length);
                                            }

                                            }


                                            As an alternative, you can make the result length a parameter to the pad(...) method. In that case do the adjustment of the hidden padding in that method instead of in the constructor.



                                            (Hint: For extra credit, make it thread-safe! ;-)






                                            share|improve this answer



















                                            • 1





                                              That is thread safe, except for unsafe publication (make your fields final, as a matter of course). I think performance could be improved by doing a substring before the + which should be replaced by concat (strangely enough).

                                              – Tom Hawtin - tackline
                                              Dec 24 '08 at 12:44
















                                            4














                                            You can reduce the per-call overhead by retaining the padding data, rather than rebuilding it every time:



                                            public class RightPadder {

                                            private int length;
                                            private String padding;

                                            public RightPadder(int length, String pad) {
                                            this.length = length;
                                            StringBuilder sb = new StringBuilder(pad);
                                            while (sb.length() < length) {
                                            sb.append(sb);
                                            }
                                            padding = sb.toString();
                                            }

                                            public String pad(String s) {
                                            return (s.length() < length ? s + padding : s).substring(0, length);
                                            }

                                            }


                                            As an alternative, you can make the result length a parameter to the pad(...) method. In that case do the adjustment of the hidden padding in that method instead of in the constructor.



                                            (Hint: For extra credit, make it thread-safe! ;-)






                                            share|improve this answer



















                                            • 1





                                              That is thread safe, except for unsafe publication (make your fields final, as a matter of course). I think performance could be improved by doing a substring before the + which should be replaced by concat (strangely enough).

                                              – Tom Hawtin - tackline
                                              Dec 24 '08 at 12:44














                                            4












                                            4








                                            4







                                            You can reduce the per-call overhead by retaining the padding data, rather than rebuilding it every time:



                                            public class RightPadder {

                                            private int length;
                                            private String padding;

                                            public RightPadder(int length, String pad) {
                                            this.length = length;
                                            StringBuilder sb = new StringBuilder(pad);
                                            while (sb.length() < length) {
                                            sb.append(sb);
                                            }
                                            padding = sb.toString();
                                            }

                                            public String pad(String s) {
                                            return (s.length() < length ? s + padding : s).substring(0, length);
                                            }

                                            }


                                            As an alternative, you can make the result length a parameter to the pad(...) method. In that case do the adjustment of the hidden padding in that method instead of in the constructor.



                                            (Hint: For extra credit, make it thread-safe! ;-)






                                            share|improve this answer













                                            You can reduce the per-call overhead by retaining the padding data, rather than rebuilding it every time:



                                            public class RightPadder {

                                            private int length;
                                            private String padding;

                                            public RightPadder(int length, String pad) {
                                            this.length = length;
                                            StringBuilder sb = new StringBuilder(pad);
                                            while (sb.length() < length) {
                                            sb.append(sb);
                                            }
                                            padding = sb.toString();
                                            }

                                            public String pad(String s) {
                                            return (s.length() < length ? s + padding : s).substring(0, length);
                                            }

                                            }


                                            As an alternative, you can make the result length a parameter to the pad(...) method. In that case do the adjustment of the hidden padding in that method instead of in the constructor.



                                            (Hint: For extra credit, make it thread-safe! ;-)







                                            share|improve this answer












                                            share|improve this answer



                                            share|improve this answer










                                            answered Dec 23 '08 at 14:25









                                            joel.neelyjoel.neely

                                            26.2k84862




                                            26.2k84862








                                            • 1





                                              That is thread safe, except for unsafe publication (make your fields final, as a matter of course). I think performance could be improved by doing a substring before the + which should be replaced by concat (strangely enough).

                                              – Tom Hawtin - tackline
                                              Dec 24 '08 at 12:44














                                            • 1





                                              That is thread safe, except for unsafe publication (make your fields final, as a matter of course). I think performance could be improved by doing a substring before the + which should be replaced by concat (strangely enough).

                                              – Tom Hawtin - tackline
                                              Dec 24 '08 at 12:44








                                            1




                                            1





                                            That is thread safe, except for unsafe publication (make your fields final, as a matter of course). I think performance could be improved by doing a substring before the + which should be replaced by concat (strangely enough).

                                            – Tom Hawtin - tackline
                                            Dec 24 '08 at 12:44





                                            That is thread safe, except for unsafe publication (make your fields final, as a matter of course). I think performance could be improved by doing a substring before the + which should be replaced by concat (strangely enough).

                                            – Tom Hawtin - tackline
                                            Dec 24 '08 at 12:44











                                            2














                                            you can use the built in StringBuilder append() and insert() methods,
                                            for padding of variable string lengths:



                                            AbstractStringBuilder append(CharSequence s, int start, int end) ;


                                            For Example:



                                            private static final String  MAX_STRING = "                    "; //20 spaces

                                            Set<StringBuilder> set= new HashSet<StringBuilder>();
                                            set.add(new StringBuilder("12345678"));
                                            set.add(new StringBuilder("123456789"));
                                            set.add(new StringBuilder("1234567811"));
                                            set.add(new StringBuilder("12345678123"));
                                            set.add(new StringBuilder("1234567812234"));
                                            set.add(new StringBuilder("1234567812222"));
                                            set.add(new StringBuilder("12345678122334"));

                                            for(StringBuilder padMe: set)
                                            padMe.append(MAX_STRING, padMe.length(), MAX_STRING.length());





                                            share|improve this answer




























                                              2














                                              you can use the built in StringBuilder append() and insert() methods,
                                              for padding of variable string lengths:



                                              AbstractStringBuilder append(CharSequence s, int start, int end) ;


                                              For Example:



                                              private static final String  MAX_STRING = "                    "; //20 spaces

                                              Set<StringBuilder> set= new HashSet<StringBuilder>();
                                              set.add(new StringBuilder("12345678"));
                                              set.add(new StringBuilder("123456789"));
                                              set.add(new StringBuilder("1234567811"));
                                              set.add(new StringBuilder("12345678123"));
                                              set.add(new StringBuilder("1234567812234"));
                                              set.add(new StringBuilder("1234567812222"));
                                              set.add(new StringBuilder("12345678122334"));

                                              for(StringBuilder padMe: set)
                                              padMe.append(MAX_STRING, padMe.length(), MAX_STRING.length());





                                              share|improve this answer


























                                                2












                                                2








                                                2







                                                you can use the built in StringBuilder append() and insert() methods,
                                                for padding of variable string lengths:



                                                AbstractStringBuilder append(CharSequence s, int start, int end) ;


                                                For Example:



                                                private static final String  MAX_STRING = "                    "; //20 spaces

                                                Set<StringBuilder> set= new HashSet<StringBuilder>();
                                                set.add(new StringBuilder("12345678"));
                                                set.add(new StringBuilder("123456789"));
                                                set.add(new StringBuilder("1234567811"));
                                                set.add(new StringBuilder("12345678123"));
                                                set.add(new StringBuilder("1234567812234"));
                                                set.add(new StringBuilder("1234567812222"));
                                                set.add(new StringBuilder("12345678122334"));

                                                for(StringBuilder padMe: set)
                                                padMe.append(MAX_STRING, padMe.length(), MAX_STRING.length());





                                                share|improve this answer













                                                you can use the built in StringBuilder append() and insert() methods,
                                                for padding of variable string lengths:



                                                AbstractStringBuilder append(CharSequence s, int start, int end) ;


                                                For Example:



                                                private static final String  MAX_STRING = "                    "; //20 spaces

                                                Set<StringBuilder> set= new HashSet<StringBuilder>();
                                                set.add(new StringBuilder("12345678"));
                                                set.add(new StringBuilder("123456789"));
                                                set.add(new StringBuilder("1234567811"));
                                                set.add(new StringBuilder("12345678123"));
                                                set.add(new StringBuilder("1234567812234"));
                                                set.add(new StringBuilder("1234567812222"));
                                                set.add(new StringBuilder("12345678122334"));

                                                for(StringBuilder padMe: set)
                                                padMe.append(MAX_STRING, padMe.length(), MAX_STRING.length());






                                                share|improve this answer












                                                share|improve this answer



                                                share|improve this answer










                                                answered Aug 24 '10 at 10:55









                                                ef_orenef_oren

                                                212




                                                212























                                                    2














                                                    This works:



                                                    "".format("%1$-" + 9 + "s", "XXX").replaceAll(" ", "0")


                                                    It will fill your String XXX up to 9 Chars with a whitespace. After that all Whitespaces will be replaced with a 0. You can change the whitespace and the 0 to whatever you want...






                                                    share|improve this answer




























                                                      2














                                                      This works:



                                                      "".format("%1$-" + 9 + "s", "XXX").replaceAll(" ", "0")


                                                      It will fill your String XXX up to 9 Chars with a whitespace. After that all Whitespaces will be replaced with a 0. You can change the whitespace and the 0 to whatever you want...






                                                      share|improve this answer


























                                                        2












                                                        2








                                                        2







                                                        This works:



                                                        "".format("%1$-" + 9 + "s", "XXX").replaceAll(" ", "0")


                                                        It will fill your String XXX up to 9 Chars with a whitespace. After that all Whitespaces will be replaced with a 0. You can change the whitespace and the 0 to whatever you want...






                                                        share|improve this answer













                                                        This works:



                                                        "".format("%1$-" + 9 + "s", "XXX").replaceAll(" ", "0")


                                                        It will fill your String XXX up to 9 Chars with a whitespace. After that all Whitespaces will be replaced with a 0. You can change the whitespace and the 0 to whatever you want...







                                                        share|improve this answer












                                                        share|improve this answer



                                                        share|improve this answer










                                                        answered May 11 '11 at 14:30









                                                        Sebastian S.Sebastian S.

                                                        128212




                                                        128212























                                                            2














                                                            public static String padLeft(String in, int size, char padChar) {                
                                                            if (in.length() <= size) {
                                                            char temp = new char[size];
                                                            /* Llenado Array con el padChar*/
                                                            for(int i =0;i<size;i++){
                                                            temp[i]= padChar;
                                                            }
                                                            int posIniTemp = size-in.length();
                                                            for(int i=0;i<in.length();i++){
                                                            temp[posIniTemp]=in.charAt(i);
                                                            posIniTemp++;
                                                            }
                                                            return new String(temp);
                                                            }
                                                            return "";
                                                            }





                                                            share|improve this answer




























                                                              2














                                                              public static String padLeft(String in, int size, char padChar) {                
                                                              if (in.length() <= size) {
                                                              char temp = new char[size];
                                                              /* Llenado Array con el padChar*/
                                                              for(int i =0;i<size;i++){
                                                              temp[i]= padChar;
                                                              }
                                                              int posIniTemp = size-in.length();
                                                              for(int i=0;i<in.length();i++){
                                                              temp[posIniTemp]=in.charAt(i);
                                                              posIniTemp++;
                                                              }
                                                              return new String(temp);
                                                              }
                                                              return "";
                                                              }





                                                              share|improve this answer


























                                                                2












                                                                2








                                                                2







                                                                public static String padLeft(String in, int size, char padChar) {                
                                                                if (in.length() <= size) {
                                                                char temp = new char[size];
                                                                /* Llenado Array con el padChar*/
                                                                for(int i =0;i<size;i++){
                                                                temp[i]= padChar;
                                                                }
                                                                int posIniTemp = size-in.length();
                                                                for(int i=0;i<in.length();i++){
                                                                temp[posIniTemp]=in.charAt(i);
                                                                posIniTemp++;
                                                                }
                                                                return new String(temp);
                                                                }
                                                                return "";
                                                                }





                                                                share|improve this answer













                                                                public static String padLeft(String in, int size, char padChar) {                
                                                                if (in.length() <= size) {
                                                                char temp = new char[size];
                                                                /* Llenado Array con el padChar*/
                                                                for(int i =0;i<size;i++){
                                                                temp[i]= padChar;
                                                                }
                                                                int posIniTemp = size-in.length();
                                                                for(int i=0;i<in.length();i++){
                                                                temp[posIniTemp]=in.charAt(i);
                                                                posIniTemp++;
                                                                }
                                                                return new String(temp);
                                                                }
                                                                return "";
                                                                }






                                                                share|improve this answer












                                                                share|improve this answer



                                                                share|improve this answer










                                                                answered Aug 24 '11 at 17:36









                                                                Marlon TaraxMarlon Tarax

                                                                211




                                                                211























                                                                    2














                                                                    Let's me leave an answer for some cases that you need to give left/right padding (or prefix/suffix string or spaces) before you concatenate to another string and you don't want to test length or any if condition.



                                                                    The same to the selected answer, I would prefer the StringUtils of Apache Commons but using this way:



                                                                    StringUtils.defaultString(StringUtils.leftPad(myString, 1))


                                                                    Explain:





                                                                    • myString: the string I input, can be null


                                                                    • StringUtils.leftPad(myString, 1): if string is null, this statement would return null too

                                                                    • then use defaultString to give empty string to prevent concatenate null






                                                                    share|improve this answer






























                                                                      2














                                                                      Let's me leave an answer for some cases that you need to give left/right padding (or prefix/suffix string or spaces) before you concatenate to another string and you don't want to test length or any if condition.



                                                                      The same to the selected answer, I would prefer the StringUtils of Apache Commons but using this way:



                                                                      StringUtils.defaultString(StringUtils.leftPad(myString, 1))


                                                                      Explain:





                                                                      • myString: the string I input, can be null


                                                                      • StringUtils.leftPad(myString, 1): if string is null, this statement would return null too

                                                                      • then use defaultString to give empty string to prevent concatenate null






                                                                      share|improve this answer




























                                                                        2












                                                                        2








                                                                        2







                                                                        Let's me leave an answer for some cases that you need to give left/right padding (or prefix/suffix string or spaces) before you concatenate to another string and you don't want to test length or any if condition.



                                                                        The same to the selected answer, I would prefer the StringUtils of Apache Commons but using this way:



                                                                        StringUtils.defaultString(StringUtils.leftPad(myString, 1))


                                                                        Explain:





                                                                        • myString: the string I input, can be null


                                                                        • StringUtils.leftPad(myString, 1): if string is null, this statement would return null too

                                                                        • then use defaultString to give empty string to prevent concatenate null






                                                                        share|improve this answer















                                                                        Let's me leave an answer for some cases that you need to give left/right padding (or prefix/suffix string or spaces) before you concatenate to another string and you don't want to test length or any if condition.



                                                                        The same to the selected answer, I would prefer the StringUtils of Apache Commons but using this way:



                                                                        StringUtils.defaultString(StringUtils.leftPad(myString, 1))


                                                                        Explain:





                                                                        • myString: the string I input, can be null


                                                                        • StringUtils.leftPad(myString, 1): if string is null, this statement would return null too

                                                                        • then use defaultString to give empty string to prevent concatenate null







                                                                        share|improve this answer














                                                                        share|improve this answer



                                                                        share|improve this answer








                                                                        edited Aug 29 '16 at 13:37









                                                                        bluish

                                                                        14k1694148




                                                                        14k1694148










                                                                        answered Aug 11 '16 at 5:09









                                                                        OsifyOsify

                                                                        1,4431834




                                                                        1,4431834























                                                                            2














                                                                            Found this on Dzone



                                                                            Pad with zeros:



                                                                            String.format("|%020d|", 93); // prints: |00000000000000000093|





                                                                            share|improve this answer
























                                                                            • This should be the answer, simple and concise, no need to install external libraries.

                                                                              – Wong Jia Hau
                                                                              Aug 27 '18 at 4:10
















                                                                            2














                                                                            Found this on Dzone



                                                                            Pad with zeros:



                                                                            String.format("|%020d|", 93); // prints: |00000000000000000093|





                                                                            share|improve this answer
























                                                                            • This should be the answer, simple and concise, no need to install external libraries.

                                                                              – Wong Jia Hau
                                                                              Aug 27 '18 at 4:10














                                                                            2












                                                                            2








                                                                            2







                                                                            Found this on Dzone



                                                                            Pad with zeros:



                                                                            String.format("|%020d|", 93); // prints: |00000000000000000093|





                                                                            share|improve this answer













                                                                            Found this on Dzone



                                                                            Pad with zeros:



                                                                            String.format("|%020d|", 93); // prints: |00000000000000000093|






                                                                            share|improve this answer












                                                                            share|improve this answer



                                                                            share|improve this answer










                                                                            answered Oct 26 '17 at 19:20









                                                                            OJVMOJVM

                                                                            6801229




                                                                            6801229













                                                                            • This should be the answer, simple and concise, no need to install external libraries.

                                                                              – Wong Jia Hau
                                                                              Aug 27 '18 at 4:10



















                                                                            • This should be the answer, simple and concise, no need to install external libraries.

                                                                              – Wong Jia Hau
                                                                              Aug 27 '18 at 4:10

















                                                                            This should be the answer, simple and concise, no need to install external libraries.

                                                                            – Wong Jia Hau
                                                                            Aug 27 '18 at 4:10





                                                                            This should be the answer, simple and concise, no need to install external libraries.

                                                                            – Wong Jia Hau
                                                                            Aug 27 '18 at 4:10











                                                                            1














                                                                            java.util.Formatter will do left and right padding. No need for odd third party dependencies (would you want to add them for something so trivial).



                                                                            [I've left out the details and made this post 'community wiki' as it is not something I have a need for.]






                                                                            share|improve this answer





















                                                                            • 4





                                                                              I disagree. In any larger Java project you will typically do such a lot of String manipulation, that the increased readability and avoidance of errors is well worth using Apache Commons Lang. You all know code like someString.subString(someString.indexOf(startCharacter), someString.lastIndexOf(endCharacter)), which can easily be avoided with StringUtils.

                                                                              – Bananeweizen
                                                                              May 30 '11 at 20:15
















                                                                            1














                                                                            java.util.Formatter will do left and right padding. No need for odd third party dependencies (would you want to add them for something so trivial).



                                                                            [I've left out the details and made this post 'community wiki' as it is not something I have a need for.]






                                                                            share|improve this answer





















                                                                            • 4





                                                                              I disagree. In any larger Java project you will typically do such a lot of String manipulation, that the increased readability and avoidance of errors is well worth using Apache Commons Lang. You all know code like someString.subString(someString.indexOf(startCharacter), someString.lastIndexOf(endCharacter)), which can easily be avoided with StringUtils.

                                                                              – Bananeweizen
                                                                              May 30 '11 at 20:15














                                                                            1












                                                                            1








                                                                            1







                                                                            java.util.Formatter will do left and right padding. No need for odd third party dependencies (would you want to add them for something so trivial).



                                                                            [I've left out the details and made this post 'community wiki' as it is not something I have a need for.]






                                                                            share|improve this answer















                                                                            java.util.Formatter will do left and right padding. No need for odd third party dependencies (would you want to add them for something so trivial).



                                                                            [I've left out the details and made this post 'community wiki' as it is not something I have a need for.]







                                                                            share|improve this answer














                                                                            share|improve this answer



                                                                            share|improve this answer








                                                                            answered Dec 23 '08 at 14:58


























                                                                            community wiki





                                                                            Tom Hawtin - tackline









                                                                            • 4





                                                                              I disagree. In any larger Java project you will typically do such a lot of String manipulation, that the increased readability and avoidance of errors is well worth using Apache Commons Lang. You all know code like someString.subString(someString.indexOf(startCharacter), someString.lastIndexOf(endCharacter)), which can easily be avoided with StringUtils.

                                                                              – Bananeweizen
                                                                              May 30 '11 at 20:15














                                                                            • 4





                                                                              I disagree. In any larger Java project you will typically do such a lot of String manipulation, that the increased readability and avoidance of errors is well worth using Apache Commons Lang. You all know code like someString.subString(someString.indexOf(startCharacter), someString.lastIndexOf(endCharacter)), which can easily be avoided with StringUtils.

                                                                              – Bananeweizen
                                                                              May 30 '11 at 20:15








                                                                            4




                                                                            4





                                                                            I disagree. In any larger Java project you will typically do such a lot of String manipulation, that the increased readability and avoidance of errors is well worth using Apache Commons Lang. You all know code like someString.subString(someString.indexOf(startCharacter), someString.lastIndexOf(endCharacter)), which can easily be avoided with StringUtils.

                                                                            – Bananeweizen
                                                                            May 30 '11 at 20:15





                                                                            I disagree. In any larger Java project you will typically do such a lot of String manipulation, that the increased readability and avoidance of errors is well worth using Apache Commons Lang. You all know code like someString.subString(someString.indexOf(startCharacter), someString.lastIndexOf(endCharacter)), which can easily be avoided with StringUtils.

                                                                            – Bananeweizen
                                                                            May 30 '11 at 20:15











                                                                            1














                                                                            @ck's and @Marlon Tarak's answers are the only ones to use a char, which for applications that have several calls to padding methods per second is the best approach. However, they don't take advantage of any array manipulation optimizations and are a little overwritten for my taste; this can be done with no loops at all.



                                                                            public static String pad(String source, char fill, int length, boolean right){
                                                                            if(source.length() > length) return source;
                                                                            char out = new char[length];
                                                                            if(right){
                                                                            System.arraycopy(source.toCharArray(), 0, out, 0, source.length());
                                                                            Arrays.fill(out, source.length(), length, fill);
                                                                            }else{
                                                                            int sourceOffset = length - source.length();
                                                                            System.arraycopy(source.toCharArray(), 0, out, sourceOffset, source.length());
                                                                            Arrays.fill(out, 0, sourceOffset, fill);
                                                                            }
                                                                            return new String(out);
                                                                            }


                                                                            Simple test method:



                                                                            public static void main(String... args){
                                                                            System.out.println("012345678901234567890123456789");
                                                                            System.out.println(pad("cats", ' ', 30, true));
                                                                            System.out.println(pad("cats", ' ', 30, false));
                                                                            System.out.println(pad("cats", ' ', 20, false));
                                                                            System.out.println(pad("cats", '$', 30, true));
                                                                            System.out.println(pad("too long for your own good, buddy", '#', 30, true));
                                                                            }


                                                                            Outputs:



                                                                            012345678901234567890123456789
                                                                            cats
                                                                            cats
                                                                            cats
                                                                            cats$$$$$$$$$$$$$$$$$$$$$$$$$$
                                                                            too long for your own good, buddy





                                                                            share|improve this answer






























                                                                              1














                                                                              @ck's and @Marlon Tarak's answers are the only ones to use a char, which for applications that have several calls to padding methods per second is the best approach. However, they don't take advantage of any array manipulation optimizations and are a little overwritten for my taste; this can be done with no loops at all.



                                                                              public static String pad(String source, char fill, int length, boolean right){
                                                                              if(source.length() > length) return source;
                                                                              char out = new char[length];
                                                                              if(right){
                                                                              System.arraycopy(source.toCharArray(), 0, out, 0, source.length());
                                                                              Arrays.fill(out, source.length(), length, fill);
                                                                              }else{
                                                                              int sourceOffset = length - source.length();
                                                                              System.arraycopy(source.toCharArray(), 0, out, sourceOffset, source.length());
                                                                              Arrays.fill(out, 0, sourceOffset, fill);
                                                                              }
                                                                              return new String(out);
                                                                              }


                                                                              Simple test method:



                                                                              public static void main(String... args){
                                                                              System.out.println("012345678901234567890123456789");
                                                                              System.out.println(pad("cats", ' ', 30, true));
                                                                              System.out.println(pad("cats", ' ', 30, false));
                                                                              System.out.println(pad("cats", ' ', 20, false));
                                                                              System.out.println(pad("cats", '$', 30, true));
                                                                              System.out.println(pad("too long for your own good, buddy", '#', 30, true));
                                                                              }


                                                                              Outputs:



                                                                              012345678901234567890123456789
                                                                              cats
                                                                              cats
                                                                              cats
                                                                              cats$$$$$$$$$$$$$$$$$$$$$$$$$$
                                                                              too long for your own good, buddy





                                                                              share|improve this answer




























                                                                                1












                                                                                1








                                                                                1







                                                                                @ck's and @Marlon Tarak's answers are the only ones to use a char, which for applications that have several calls to padding methods per second is the best approach. However, they don't take advantage of any array manipulation optimizations and are a little overwritten for my taste; this can be done with no loops at all.



                                                                                public static String pad(String source, char fill, int length, boolean right){
                                                                                if(source.length() > length) return source;
                                                                                char out = new char[length];
                                                                                if(right){
                                                                                System.arraycopy(source.toCharArray(), 0, out, 0, source.length());
                                                                                Arrays.fill(out, source.length(), length, fill);
                                                                                }else{
                                                                                int sourceOffset = length - source.length();
                                                                                System.arraycopy(source.toCharArray(), 0, out, sourceOffset, source.length());
                                                                                Arrays.fill(out, 0, sourceOffset, fill);
                                                                                }
                                                                                return new String(out);
                                                                                }


                                                                                Simple test method:



                                                                                public static void main(String... args){
                                                                                System.out.println("012345678901234567890123456789");
                                                                                System.out.println(pad("cats", ' ', 30, true));
                                                                                System.out.println(pad("cats", ' ', 30, false));
                                                                                System.out.println(pad("cats", ' ', 20, false));
                                                                                System.out.println(pad("cats", '$', 30, true));
                                                                                System.out.println(pad("too long for your own good, buddy", '#', 30, true));
                                                                                }


                                                                                Outputs:



                                                                                012345678901234567890123456789
                                                                                cats
                                                                                cats
                                                                                cats
                                                                                cats$$$$$$$$$$$$$$$$$$$$$$$$$$
                                                                                too long for your own good, buddy





                                                                                share|improve this answer















                                                                                @ck's and @Marlon Tarak's answers are the only ones to use a char, which for applications that have several calls to padding methods per second is the best approach. However, they don't take advantage of any array manipulation optimizations and are a little overwritten for my taste; this can be done with no loops at all.



                                                                                public static String pad(String source, char fill, int length, boolean right){
                                                                                if(source.length() > length) return source;
                                                                                char out = new char[length];
                                                                                if(right){
                                                                                System.arraycopy(source.toCharArray(), 0, out, 0, source.length());
                                                                                Arrays.fill(out, source.length(), length, fill);
                                                                                }else{
                                                                                int sourceOffset = length - source.length();
                                                                                System.arraycopy(source.toCharArray(), 0, out, sourceOffset, source.length());
                                                                                Arrays.fill(out, 0, sourceOffset, fill);
                                                                                }
                                                                                return new String(out);
                                                                                }


                                                                                Simple test method:



                                                                                public static void main(String... args){
                                                                                System.out.println("012345678901234567890123456789");
                                                                                System.out.println(pad("cats", ' ', 30, true));
                                                                                System.out.println(pad("cats", ' ', 30, false));
                                                                                System.out.println(pad("cats", ' ', 20, false));
                                                                                System.out.println(pad("cats", '$', 30, true));
                                                                                System.out.println(pad("too long for your own good, buddy", '#', 30, true));
                                                                                }


                                                                                Outputs:



                                                                                012345678901234567890123456789
                                                                                cats
                                                                                cats
                                                                                cats
                                                                                cats$$$$$$$$$$$$$$$$$$$$$$$$$$
                                                                                too long for your own good, buddy






                                                                                share|improve this answer














                                                                                share|improve this answer



                                                                                share|improve this answer








                                                                                edited Jul 11 '17 at 20:45

























                                                                                answered Jul 11 '17 at 20:39









                                                                                ndm13ndm13

                                                                                8071218




                                                                                8071218























                                                                                    1














                                                                                    Use this function.



                                                                                    private String leftPadding(String word, int length, char ch) {
                                                                                    return (length > word.length()) ? leftPadding(ch + word, length, ch) : word;
                                                                                    }


                                                                                    how to use?



                                                                                    leftPadding(month, 2, '0');


                                                                                    output:
                                                                                    01 02 03 04 .. 11 12






                                                                                    share|improve this answer






























                                                                                      1














                                                                                      Use this function.



                                                                                      private String leftPadding(String word, int length, char ch) {
                                                                                      return (length > word.length()) ? leftPadding(ch + word, length, ch) : word;
                                                                                      }


                                                                                      how to use?



                                                                                      leftPadding(month, 2, '0');


                                                                                      output:
                                                                                      01 02 03 04 .. 11 12






                                                                                      share|improve this answer




























                                                                                        1












                                                                                        1








                                                                                        1







                                                                                        Use this function.



                                                                                        private String leftPadding(String word, int length, char ch) {
                                                                                        return (length > word.length()) ? leftPadding(ch + word, length, ch) : word;
                                                                                        }


                                                                                        how to use?



                                                                                        leftPadding(month, 2, '0');


                                                                                        output:
                                                                                        01 02 03 04 .. 11 12






                                                                                        share|improve this answer















                                                                                        Use this function.



                                                                                        private String leftPadding(String word, int length, char ch) {
                                                                                        return (length > word.length()) ? leftPadding(ch + word, length, ch) : word;
                                                                                        }


                                                                                        how to use?



                                                                                        leftPadding(month, 2, '0');


                                                                                        output:
                                                                                        01 02 03 04 .. 11 12







                                                                                        share|improve this answer














                                                                                        share|improve this answer



                                                                                        share|improve this answer








                                                                                        edited Dec 2 '17 at 9:51

























                                                                                        answered Nov 30 '17 at 8:06









                                                                                        Samet öztoprakSamet öztoprak

                                                                                        6511816




                                                                                        6511816























                                                                                            1














                                                                                            A lot of people have some very interesting techniques but I like to keep it simple so I go with this :



                                                                                            public static String padRight(String s, int n, char padding){
                                                                                            StringBuilder builder = new StringBuilder(s.length() + n);
                                                                                            builder.append(s);
                                                                                            for(int i = 0; i < n; i++){
                                                                                            builder.append(padding);
                                                                                            }
                                                                                            return builder.toString();
                                                                                            }

                                                                                            public static String padLeft(String s, int n, char padding) {
                                                                                            StringBuilder builder = new StringBuilder(s.length() + n);
                                                                                            for(int i = 0; i < n; i++){
                                                                                            builder.append(Character.toString(padding));
                                                                                            }
                                                                                            return builder.append(s).toString();
                                                                                            }

                                                                                            public static String pad(String s, int n, char padding){
                                                                                            StringBuilder pad = new StringBuilder(s.length() + n * 2);
                                                                                            StringBuilder value = new StringBuilder(n);
                                                                                            for(int i = 0; i < n; i++){
                                                                                            pad.append(padding);
                                                                                            }
                                                                                            return value.append(pad).append(s).append(pad).toString();
                                                                                            }





                                                                                            share|improve this answer





















                                                                                            • 2





                                                                                              This is very inefficient, you should use a StringBuilder

                                                                                              – wkarl
                                                                                              Feb 25 '16 at 10:23











                                                                                            • Since you already know the length, you should tell the StringBuilder to allocate that much space when you instantiate it.

                                                                                              – Ariel
                                                                                              Jun 15 '18 at 0:28











                                                                                            • @Ariel interesting that you mention that because I was just talking to someone else about that today lol.

                                                                                              – Aelphaeis
                                                                                              Jun 15 '18 at 19:05


















                                                                                            1














                                                                                            A lot of people have some very interesting techniques but I like to keep it simple so I go with this :



                                                                                            public static String padRight(String s, int n, char padding){
                                                                                            StringBuilder builder = new StringBuilder(s.length() + n);
                                                                                            builder.append(s);
                                                                                            for(int i = 0; i < n; i++){
                                                                                            builder.append(padding);
                                                                                            }
                                                                                            return builder.toString();
                                                                                            }

                                                                                            public static String padLeft(String s, int n, char padding) {
                                                                                            StringBuilder builder = new StringBuilder(s.length() + n);
                                                                                            for(int i = 0; i < n; i++){
                                                                                            builder.append(Character.toString(padding));
                                                                                            }
                                                                                            return builder.append(s).toString();
                                                                                            }

                                                                                            public static String pad(String s, int n, char padding){
                                                                                            StringBuilder pad = new StringBuilder(s.length() + n * 2);
                                                                                            StringBuilder value = new StringBuilder(n);
                                                                                            for(int i = 0; i < n; i++){
                                                                                            pad.append(padding);
                                                                                            }
                                                                                            return value.append(pad).append(s).append(pad).toString();
                                                                                            }





                                                                                            share|improve this answer





















                                                                                            • 2





                                                                                              This is very inefficient, you should use a StringBuilder

                                                                                              – wkarl
                                                                                              Feb 25 '16 at 10:23











                                                                                            • Since you already know the length, you should tell the StringBuilder to allocate that much space when you instantiate it.

                                                                                              – Ariel
                                                                                              Jun 15 '18 at 0:28











                                                                                            • @Ariel interesting that you mention that because I was just talking to someone else about that today lol.

                                                                                              – Aelphaeis
                                                                                              Jun 15 '18 at 19:05
















                                                                                            1












                                                                                            1








                                                                                            1







                                                                                            A lot of people have some very interesting techniques but I like to keep it simple so I go with this :



                                                                                            public static String padRight(String s, int n, char padding){
                                                                                            StringBuilder builder = new StringBuilder(s.length() + n);
                                                                                            builder.append(s);
                                                                                            for(int i = 0; i < n; i++){
                                                                                            builder.append(padding);
                                                                                            }
                                                                                            return builder.toString();
                                                                                            }

                                                                                            public static String padLeft(String s, int n, char padding) {
                                                                                            StringBuilder builder = new StringBuilder(s.length() + n);
                                                                                            for(int i = 0; i < n; i++){
                                                                                            builder.append(Character.toString(padding));
                                                                                            }
                                                                                            return builder.append(s).toString();
                                                                                            }

                                                                                            public static String pad(String s, int n, char padding){
                                                                                            StringBuilder pad = new StringBuilder(s.length() + n * 2);
                                                                                            StringBuilder value = new StringBuilder(n);
                                                                                            for(int i = 0; i < n; i++){
                                                                                            pad.append(padding);
                                                                                            }
                                                                                            return value.append(pad).append(s).append(pad).toString();
                                                                                            }





                                                                                            share|improve this answer















                                                                                            A lot of people have some very interesting techniques but I like to keep it simple so I go with this :



                                                                                            public static String padRight(String s, int n, char padding){
                                                                                            StringBuilder builder = new StringBuilder(s.length() + n);
                                                                                            builder.append(s);
                                                                                            for(int i = 0; i < n; i++){
                                                                                            builder.append(padding);
                                                                                            }
                                                                                            return builder.toString();
                                                                                            }

                                                                                            public static String padLeft(String s, int n, char padding) {
                                                                                            StringBuilder builder = new StringBuilder(s.length() + n);
                                                                                            for(int i = 0; i < n; i++){
                                                                                            builder.append(Character.toString(padding));
                                                                                            }
                                                                                            return builder.append(s).toString();
                                                                                            }

                                                                                            public static String pad(String s, int n, char padding){
                                                                                            StringBuilder pad = new StringBuilder(s.length() + n * 2);
                                                                                            StringBuilder value = new StringBuilder(n);
                                                                                            for(int i = 0; i < n; i++){
                                                                                            pad.append(padding);
                                                                                            }
                                                                                            return value.append(pad).append(s).append(pad).toString();
                                                                                            }






                                                                                            share|improve this answer














                                                                                            share|improve this answer



                                                                                            share|improve this answer








                                                                                            edited Jun 17 '18 at 15:24

























                                                                                            answered Aug 28 '15 at 16:58









                                                                                            AelphaeisAelphaeis

                                                                                            1,74221834




                                                                                            1,74221834








                                                                                            • 2





                                                                                              This is very inefficient, you should use a StringBuilder

                                                                                              – wkarl
                                                                                              Feb 25 '16 at 10:23











                                                                                            • Since you already know the length, you should tell the StringBuilder to allocate that much space when you instantiate it.

                                                                                              – Ariel
                                                                                              Jun 15 '18 at 0:28











                                                                                            • @Ariel interesting that you mention that because I was just talking to someone else about that today lol.

                                                                                              – Aelphaeis
                                                                                              Jun 15 '18 at 19:05
















                                                                                            • 2





                                                                                              This is very inefficient, you should use a StringBuilder

                                                                                              – wkarl
                                                                                              Feb 25 '16 at 10:23











                                                                                            • Since you already know the length, you should tell the StringBuilder to allocate that much space when you instantiate it.

                                                                                              – Ariel
                                                                                              Jun 15 '18 at 0:28











                                                                                            • @Ariel interesting that you mention that because I was just talking to someone else about that today lol.

                                                                                              – Aelphaeis
                                                                                              Jun 15 '18 at 19:05










                                                                                            2




                                                                                            2





                                                                                            This is very inefficient, you should use a StringBuilder

                                                                                            – wkarl
                                                                                            Feb 25 '16 at 10:23





                                                                                            This is very inefficient, you should use a StringBuilder

                                                                                            – wkarl
                                                                                            Feb 25 '16 at 10:23













                                                                                            Since you already know the length, you should tell the StringBuilder to allocate that much space when you instantiate it.

                                                                                            – Ariel
                                                                                            Jun 15 '18 at 0:28





                                                                                            Since you already know the length, you should tell the StringBuilder to allocate that much space when you instantiate it.

                                                                                            – Ariel
                                                                                            Jun 15 '18 at 0:28













                                                                                            @Ariel interesting that you mention that because I was just talking to someone else about that today lol.

                                                                                            – Aelphaeis
                                                                                            Jun 15 '18 at 19:05







                                                                                            @Ariel interesting that you mention that because I was just talking to someone else about that today lol.

                                                                                            – Aelphaeis
                                                                                            Jun 15 '18 at 19:05













                                                                                            0














                                                                                            A simple solution without any API will be as follows:



                                                                                            public String pad(String num, int len){
                                                                                            if(len-num.length() <=0) return num;
                                                                                            StringBuffer sb = new StringBuffer();
                                                                                            for(i=0; i<(len-num.length()); i++){
                                                                                            sb.append("0");
                                                                                            }
                                                                                            sb.append(num);
                                                                                            return sb.toString();
                                                                                            }





                                                                                            share|improve this answer






























                                                                                              0














                                                                                              A simple solution without any API will be as follows:



                                                                                              public String pad(String num, int len){
                                                                                              if(len-num.length() <=0) return num;
                                                                                              StringBuffer sb = new StringBuffer();
                                                                                              for(i=0; i<(len-num.length()); i++){
                                                                                              sb.append("0");
                                                                                              }
                                                                                              sb.append(num);
                                                                                              return sb.toString();
                                                                                              }





                                                                                              share|improve this answer




























                                                                                                0












                                                                                                0








                                                                                                0







                                                                                                A simple solution without any API will be as follows:



                                                                                                public String pad(String num, int len){
                                                                                                if(len-num.length() <=0) return num;
                                                                                                StringBuffer sb = new StringBuffer();
                                                                                                for(i=0; i<(len-num.length()); i++){
                                                                                                sb.append("0");
                                                                                                }
                                                                                                sb.append(num);
                                                                                                return sb.toString();
                                                                                                }





                                                                                                share|improve this answer















                                                                                                A simple solution without any API will be as follows:



                                                                                                public String pad(String num, int len){
                                                                                                if(len-num.length() <=0) return num;
                                                                                                StringBuffer sb = new StringBuffer();
                                                                                                for(i=0; i<(len-num.length()); i++){
                                                                                                sb.append("0");
                                                                                                }
                                                                                                sb.append(num);
                                                                                                return sb.toString();
                                                                                                }






                                                                                                share|improve this answer














                                                                                                share|improve this answer



                                                                                                share|improve this answer








                                                                                                edited May 17 '17 at 13:07









                                                                                                bluish

                                                                                                14k1694148




                                                                                                14k1694148










                                                                                                answered May 6 '17 at 4:17









                                                                                                Shashank ShekharShashank Shekhar

                                                                                                112




                                                                                                112























                                                                                                    0














                                                                                                    Java oneliners, no fancy library.



                                                                                                    // 6 characters padding example
                                                                                                    String pad = "******";
                                                                                                    // testcases for 0, 4, 8 characters
                                                                                                    String input = "" | "abcd" | "abcdefgh"


                                                                                                    Pad Left, don't limit



                                                                                                    result = pad.substring(Math.min(input.length(),pad.length())) + input;
                                                                                                    results: "******" | "**abcd" | "abcdefgh"


                                                                                                    Pad Right, don't limit



                                                                                                    result = input + pad.substring(Math.min(input.length(),pad.length()));
                                                                                                    results: "******" | "abcd**" | "abcdefgh"


                                                                                                    Pad Left, limit to pad length



                                                                                                    result = (pad + input).substring(input.length(), input.length() + pad.length());
                                                                                                    results: "******" | "**abcd" | "cdefgh"


                                                                                                    Pad Right, limit to pad length



                                                                                                    result = (input + pad).substring(0, pad.length());
                                                                                                    results: "******" | "abcd**" | "abcdef"





                                                                                                    share|improve this answer




























                                                                                                      0














                                                                                                      Java oneliners, no fancy library.



                                                                                                      // 6 characters padding example
                                                                                                      String pad = "******";
                                                                                                      // testcases for 0, 4, 8 characters
                                                                                                      String input = "" | "abcd" | "abcdefgh"


                                                                                                      Pad Left, don't limit



                                                                                                      result = pad.substring(Math.min(input.length(),pad.length())) + input;
                                                                                                      results: "******" | "**abcd" | "abcdefgh"


                                                                                                      Pad Right, don't limit



                                                                                                      result = input + pad.substring(Math.min(input.length(),pad.length()));
                                                                                                      results: "******" | "abcd**" | "abcdefgh"


                                                                                                      Pad Left, limit to pad length



                                                                                                      result = (pad + input).substring(input.length(), input.length() + pad.length());
                                                                                                      results: "******" | "**abcd" | "cdefgh"


                                                                                                      Pad Right, limit to pad length



                                                                                                      result = (input + pad).substring(0, pad.length());
                                                                                                      results: "******" | "abcd**" | "abcdef"





                                                                                                      share|improve this answer


























                                                                                                        0












                                                                                                        0








                                                                                                        0







                                                                                                        Java oneliners, no fancy library.



                                                                                                        // 6 characters padding example
                                                                                                        String pad = "******";
                                                                                                        // testcases for 0, 4, 8 characters
                                                                                                        String input = "" | "abcd" | "abcdefgh"


                                                                                                        Pad Left, don't limit



                                                                                                        result = pad.substring(Math.min(input.length(),pad.length())) + input;
                                                                                                        results: "******" | "**abcd" | "abcdefgh"


                                                                                                        Pad Right, don't limit



                                                                                                        result = input + pad.substring(Math.min(input.length(),pad.length()));
                                                                                                        results: "******" | "abcd**" | "abcdefgh"


                                                                                                        Pad Left, limit to pad length



                                                                                                        result = (pad + input).substring(input.length(), input.length() + pad.length());
                                                                                                        results: "******" | "**abcd" | "cdefgh"


                                                                                                        Pad Right, limit to pad length



                                                                                                        result = (input + pad).substring(0, pad.length());
                                                                                                        results: "******" | "abcd**" | "abcdef"





                                                                                                        share|improve this answer













                                                                                                        Java oneliners, no fancy library.



                                                                                                        // 6 characters padding example
                                                                                                        String pad = "******";
                                                                                                        // testcases for 0, 4, 8 characters
                                                                                                        String input = "" | "abcd" | "abcdefgh"


                                                                                                        Pad Left, don't limit



                                                                                                        result = pad.substring(Math.min(input.length(),pad.length())) + input;
                                                                                                        results: "******" | "**abcd" | "abcdefgh"


                                                                                                        Pad Right, don't limit



                                                                                                        result = input + pad.substring(Math.min(input.length(),pad.length()));
                                                                                                        results: "******" | "abcd**" | "abcdefgh"


                                                                                                        Pad Left, limit to pad length



                                                                                                        result = (pad + input).substring(input.length(), input.length() + pad.length());
                                                                                                        results: "******" | "**abcd" | "cdefgh"


                                                                                                        Pad Right, limit to pad length



                                                                                                        result = (input + pad).substring(0, pad.length());
                                                                                                        results: "******" | "abcd**" | "abcdef"






                                                                                                        share|improve this answer












                                                                                                        share|improve this answer



                                                                                                        share|improve this answer










                                                                                                        answered Aug 31 '17 at 21:49









                                                                                                        leoleo

                                                                                                        2,58721415




                                                                                                        2,58721415























                                                                                                            0














                                                                                                            All string operation usually needs to be very efficient - especially if you are working with big sets of data. I wanted something that's fast and flexible, similar to what you will get in plsql pad command. Also, I don't want to include a huge lib for just one small thing. With these considerations none of these solutions were satisfactory. This is the solutions I came up with, that had the best bench-marking results, if anybody can improve on it, please add your comment.



                                                                                                            public static char lpad(char pStringChar, int pTotalLength, char pPad) {
                                                                                                            if (pStringChar.length < pTotalLength) {
                                                                                                            char retChar = new char[pTotalLength];
                                                                                                            int padIdx = pTotalLength - pStringChar.length;
                                                                                                            Arrays.fill(retChar, 0, padIdx, pPad);
                                                                                                            System.arraycopy(pStringChar, 0, retChar, padIdx, pStringChar.length);
                                                                                                            return retChar;
                                                                                                            } else {
                                                                                                            return pStringChar;
                                                                                                            }
                                                                                                            }



                                                                                                            • note it is called with String.toCharArray() and the result can be converted to String with new String((char)result). The reason for this is, if you applying multiple operations you can do them all on char and not keep on converting between formats - behind the scenes, String is stored as char. If these operations were included in the String class itself, it would have been twice as efficient - speed and memory wise.






                                                                                                            share|improve this answer




























                                                                                                              0














                                                                                                              All string operation usually needs to be very efficient - especially if you are working with big sets of data. I wanted something that's fast and flexible, similar to what you will get in plsql pad command. Also, I don't want to include a huge lib for just one small thing. With these considerations none of these solutions were satisfactory. This is the solutions I came up with, that had the best bench-marking results, if anybody can improve on it, please add your comment.



                                                                                                              public static char lpad(char pStringChar, int pTotalLength, char pPad) {
                                                                                                              if (pStringChar.length < pTotalLength) {
                                                                                                              char retChar = new char[pTotalLength];
                                                                                                              int padIdx = pTotalLength - pStringChar.length;
                                                                                                              Arrays.fill(retChar, 0, padIdx, pPad);
                                                                                                              System.arraycopy(pStringChar, 0, retChar, padIdx, pStringChar.length);
                                                                                                              return retChar;
                                                                                                              } else {
                                                                                                              return pStringChar;
                                                                                                              }
                                                                                                              }



                                                                                                              • note it is called with String.toCharArray() and the result can be converted to String with new String((char)result). The reason for this is, if you applying multiple operations you can do them all on char and not keep on converting between formats - behind the scenes, String is stored as char. If these operations were included in the String class itself, it would have been twice as efficient - speed and memory wise.






                                                                                                              share|improve this answer


























                                                                                                                0












                                                                                                                0








                                                                                                                0







                                                                                                                All string operation usually needs to be very efficient - especially if you are working with big sets of data. I wanted something that's fast and flexible, similar to what you will get in plsql pad command. Also, I don't want to include a huge lib for just one small thing. With these considerations none of these solutions were satisfactory. This is the solutions I came up with, that had the best bench-marking results, if anybody can improve on it, please add your comment.



                                                                                                                public static char lpad(char pStringChar, int pTotalLength, char pPad) {
                                                                                                                if (pStringChar.length < pTotalLength) {
                                                                                                                char retChar = new char[pTotalLength];
                                                                                                                int padIdx = pTotalLength - pStringChar.length;
                                                                                                                Arrays.fill(retChar, 0, padIdx, pPad);
                                                                                                                System.arraycopy(pStringChar, 0, retChar, padIdx, pStringChar.length);
                                                                                                                return retChar;
                                                                                                                } else {
                                                                                                                return pStringChar;
                                                                                                                }
                                                                                                                }



                                                                                                                • note it is called with String.toCharArray() and the result can be converted to String with new String((char)result). The reason for this is, if you applying multiple operations you can do them all on char and not keep on converting between formats - behind the scenes, String is stored as char. If these operations were included in the String class itself, it would have been twice as efficient - speed and memory wise.






                                                                                                                share|improve this answer













                                                                                                                All string operation usually needs to be very efficient - especially if you are working with big sets of data. I wanted something that's fast and flexible, similar to what you will get in plsql pad command. Also, I don't want to include a huge lib for just one small thing. With these considerations none of these solutions were satisfactory. This is the solutions I came up with, that had the best bench-marking results, if anybody can improve on it, please add your comment.



                                                                                                                public static char lpad(char pStringChar, int pTotalLength, char pPad) {
                                                                                                                if (pStringChar.length < pTotalLength) {
                                                                                                                char retChar = new char[pTotalLength];
                                                                                                                int padIdx = pTotalLength - pStringChar.length;
                                                                                                                Arrays.fill(retChar, 0, padIdx, pPad);
                                                                                                                System.arraycopy(pStringChar, 0, retChar, padIdx, pStringChar.length);
                                                                                                                return retChar;
                                                                                                                } else {
                                                                                                                return pStringChar;
                                                                                                                }
                                                                                                                }



                                                                                                                • note it is called with String.toCharArray() and the result can be converted to String with new String((char)result). The reason for this is, if you applying multiple operations you can do them all on char and not keep on converting between formats - behind the scenes, String is stored as char. If these operations were included in the String class itself, it would have been twice as efficient - speed and memory wise.







                                                                                                                share|improve this answer












                                                                                                                share|improve this answer



                                                                                                                share|improve this answer










                                                                                                                answered Sep 14 '17 at 7:25









                                                                                                                EarlBEarlB

                                                                                                                216




                                                                                                                216























                                                                                                                    0














                                                                                                                    Since Java 11, String.repeat(int) can be used to left/right pad a given string.



                                                                                                                    System.out.println("*".repeat(5)+"apple");
                                                                                                                    System.out.println("apple"+"*".repeat(5));


                                                                                                                    Output:



                                                                                                                    *****apple
                                                                                                                    apple*****





                                                                                                                    share|improve this answer




























                                                                                                                      0














                                                                                                                      Since Java 11, String.repeat(int) can be used to left/right pad a given string.



                                                                                                                      System.out.println("*".repeat(5)+"apple");
                                                                                                                      System.out.println("apple"+"*".repeat(5));


                                                                                                                      Output:



                                                                                                                      *****apple
                                                                                                                      apple*****





                                                                                                                      share|improve this answer


























                                                                                                                        0












                                                                                                                        0








                                                                                                                        0







                                                                                                                        Since Java 11, String.repeat(int) can be used to left/right pad a given string.



                                                                                                                        System.out.println("*".repeat(5)+"apple");
                                                                                                                        System.out.println("apple"+"*".repeat(5));


                                                                                                                        Output:



                                                                                                                        *****apple
                                                                                                                        apple*****





                                                                                                                        share|improve this answer













                                                                                                                        Since Java 11, String.repeat(int) can be used to left/right pad a given string.



                                                                                                                        System.out.println("*".repeat(5)+"apple");
                                                                                                                        System.out.println("apple"+"*".repeat(5));


                                                                                                                        Output:



                                                                                                                        *****apple
                                                                                                                        apple*****






                                                                                                                        share|improve this answer












                                                                                                                        share|improve this answer



                                                                                                                        share|improve this answer










                                                                                                                        answered Nov 24 '18 at 14:50









                                                                                                                        Eko SetiawanEko Setiawan

                                                                                                                        205




                                                                                                                        205























                                                                                                                            -1














                                                                                                                            A simple solution would be:



                                                                                                                            package nl;
                                                                                                                            public class Padder {
                                                                                                                            public static void main(String args) {
                                                                                                                            String s = "123" ;
                                                                                                                            System.out.println("#"+(" " + s).substring(s.length())+"#");
                                                                                                                            }
                                                                                                                            }





                                                                                                                            share|improve this answer




























                                                                                                                              -1














                                                                                                                              A simple solution would be:



                                                                                                                              package nl;
                                                                                                                              public class Padder {
                                                                                                                              public static void main(String args) {
                                                                                                                              String s = "123" ;
                                                                                                                              System.out.println("#"+(" " + s).substring(s.length())+"#");
                                                                                                                              }
                                                                                                                              }





                                                                                                                              share|improve this answer


























                                                                                                                                -1












                                                                                                                                -1








                                                                                                                                -1







                                                                                                                                A simple solution would be:



                                                                                                                                package nl;
                                                                                                                                public class Padder {
                                                                                                                                public static void main(String args) {
                                                                                                                                String s = "123" ;
                                                                                                                                System.out.println("#"+(" " + s).substring(s.length())+"#");
                                                                                                                                }
                                                                                                                                }





                                                                                                                                share|improve this answer













                                                                                                                                A simple solution would be:



                                                                                                                                package nl;
                                                                                                                                public class Padder {
                                                                                                                                public static void main(String args) {
                                                                                                                                String s = "123" ;
                                                                                                                                System.out.println("#"+(" " + s).substring(s.length())+"#");
                                                                                                                                }
                                                                                                                                }






                                                                                                                                share|improve this answer












                                                                                                                                share|improve this answer



                                                                                                                                share|improve this answer










                                                                                                                                answered Jan 19 '12 at 12:24









                                                                                                                                Hans AndewegHans Andeweg

                                                                                                                                9




                                                                                                                                9























                                                                                                                                    -2














                                                                                                                                    How is this



                                                                                                                                    String is "hello" and required padding is 15 with "0" left pad



                                                                                                                                    String ax="Hello";
                                                                                                                                    while(ax.length() < 15) ax="0"+ax;





                                                                                                                                    share|improve this answer
























                                                                                                                                    • I liked this one. :)

                                                                                                                                      – null
                                                                                                                                      Mar 28 '14 at 7:37






                                                                                                                                    • 8





                                                                                                                                      this one generates up to 15 new strings.

                                                                                                                                      – claj
                                                                                                                                      Apr 14 '14 at 8:54











                                                                                                                                    • @claj Yes, but this.

                                                                                                                                      – ruffin
                                                                                                                                      Nov 15 '16 at 3:23
















                                                                                                                                    -2














                                                                                                                                    How is this



                                                                                                                                    String is "hello" and required padding is 15 with "0" left pad



                                                                                                                                    String ax="Hello";
                                                                                                                                    while(ax.length() < 15) ax="0"+ax;





                                                                                                                                    share|improve this answer
























                                                                                                                                    • I liked this one. :)

                                                                                                                                      – null
                                                                                                                                      Mar 28 '14 at 7:37






                                                                                                                                    • 8





                                                                                                                                      this one generates up to 15 new strings.

                                                                                                                                      – claj
                                                                                                                                      Apr 14 '14 at 8:54











                                                                                                                                    • @claj Yes, but this.

                                                                                                                                      – ruffin
                                                                                                                                      Nov 15 '16 at 3:23














                                                                                                                                    -2












                                                                                                                                    -2








                                                                                                                                    -2







                                                                                                                                    How is this



                                                                                                                                    String is "hello" and required padding is 15 with "0" left pad



                                                                                                                                    String ax="Hello";
                                                                                                                                    while(ax.length() < 15) ax="0"+ax;





                                                                                                                                    share|improve this answer













                                                                                                                                    How is this



                                                                                                                                    String is "hello" and required padding is 15 with "0" left pad



                                                                                                                                    String ax="Hello";
                                                                                                                                    while(ax.length() < 15) ax="0"+ax;






                                                                                                                                    share|improve this answer












                                                                                                                                    share|improve this answer



                                                                                                                                    share|improve this answer










                                                                                                                                    answered Mar 28 '13 at 11:53









                                                                                                                                    SatwantSatwant

                                                                                                                                    231




                                                                                                                                    231













                                                                                                                                    • I liked this one. :)

                                                                                                                                      – null
                                                                                                                                      Mar 28 '14 at 7:37






                                                                                                                                    • 8





                                                                                                                                      this one generates up to 15 new strings.

                                                                                                                                      – claj
                                                                                                                                      Apr 14 '14 at 8:54











                                                                                                                                    • @claj Yes, but this.

                                                                                                                                      – ruffin
                                                                                                                                      Nov 15 '16 at 3:23



















                                                                                                                                    • I liked this one. :)

                                                                                                                                      – null
                                                                                                                                      Mar 28 '14 at 7:37






                                                                                                                                    • 8





                                                                                                                                      this one generates up to 15 new strings.

                                                                                                                                      – claj
                                                                                                                                      Apr 14 '14 at 8:54











                                                                                                                                    • @claj Yes, but this.

                                                                                                                                      – ruffin
                                                                                                                                      Nov 15 '16 at 3:23

















                                                                                                                                    I liked this one. :)

                                                                                                                                    – null
                                                                                                                                    Mar 28 '14 at 7:37





                                                                                                                                    I liked this one. :)

                                                                                                                                    – null
                                                                                                                                    Mar 28 '14 at 7:37




                                                                                                                                    8




                                                                                                                                    8





                                                                                                                                    this one generates up to 15 new strings.

                                                                                                                                    – claj
                                                                                                                                    Apr 14 '14 at 8:54





                                                                                                                                    this one generates up to 15 new strings.

                                                                                                                                    – claj
                                                                                                                                    Apr 14 '14 at 8:54













                                                                                                                                    @claj Yes, but this.

                                                                                                                                    – ruffin
                                                                                                                                    Nov 15 '16 at 3:23





                                                                                                                                    @claj Yes, but this.

                                                                                                                                    – ruffin
                                                                                                                                    Nov 15 '16 at 3:23


















                                                                                                                                    draft saved

                                                                                                                                    draft discarded




















































                                                                                                                                    Thanks for contributing an answer to Stack Overflow!


                                                                                                                                    • Please be sure to answer the question. Provide details and share your research!

                                                                                                                                    But avoid



                                                                                                                                    • Asking for help, clarification, or responding to other answers.

                                                                                                                                    • Making statements based on opinion; back them up with references or personal experience.


                                                                                                                                    To learn more, see our tips on writing great answers.




                                                                                                                                    draft saved


                                                                                                                                    draft discarded














                                                                                                                                    StackExchange.ready(
                                                                                                                                    function () {
                                                                                                                                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f388461%2fhow-can-i-pad-a-string-in-java%23new-answer', 'question_page');
                                                                                                                                    }
                                                                                                                                    );

                                                                                                                                    Post as a guest















                                                                                                                                    Required, but never shown





















































                                                                                                                                    Required, but never shown














                                                                                                                                    Required, but never shown












                                                                                                                                    Required, but never shown







                                                                                                                                    Required, but never shown

































                                                                                                                                    Required, but never shown














                                                                                                                                    Required, but never shown












                                                                                                                                    Required, but never shown







                                                                                                                                    Required, but never shown







                                                                                                                                    Popular posts from this blog

                                                                                                                                    Futebolista

                                                                                                                                    Feedback on college project

                                                                                                                                    Albești (Vaslui)