213

Here is the String, for example:

"Apple"

and I would like to add zero to fill in 8 chars:

"000Apple"

How can I do so?

Elrond_EGLDer
  • 47,430
  • 25
  • 189
  • 180
Roy
  • 2,161
  • 2
  • 14
  • 7

23 Answers23

346
public class LeadingZerosExample {
    public static void main(String[] args) {
       int number = 1500;

       // String format below will add leading zeros (the %0 syntax) 
       // to the number above. 
       // The length of the formatted string will be 7 characters.

       String formatted = String.format("%07d", number);

       System.out.println("Number with leading zeros: " + formatted);
    }
}
rrufai
  • 1,455
  • 14
  • 26
Alex Rashkov
  • 9,125
  • 3
  • 28
  • 57
  • 17
    but I would like to adding leading zero before a string instead of an int. – Roy Oct 29 '10 at 12:43
  • 1
    You can use StringUtils or DecimalFormat for Java 1.4 and below. Check here http://javadevnotes.com/java-integer-to-string-with-leading-zeros – JavaDev Mar 05 '15 at 03:40
  • 3
    @Variag use `%07s` instead of `%07d`, you will get a `FormatFlagsConversionMismatchException`. you can try it. – Z fp Sep 04 '19 at 02:09
302

In case you have to do it without the help of a library:

("00000000" + "Apple").substring("Apple".length())

(Works, as long as your String isn't longer than 8 chars.)

Chris Lercher
  • 36,020
  • 19
  • 96
  • 128
  • 21
    That's pretty clever -- but it took me about 30 seconds to "get it". I think a more readable solution would be better. – Amy B Oct 29 '10 at 13:12
  • 3
    This is an -excellent- solution when you are embedding software on something without much space and the extra libraries just aren't an option. Thanks!! – Casey Murray Dec 27 '13 at 23:39
  • This version is crazy fast! I love it. – Dakkaron Jul 02 '14 at 20:18
  • This is fast & works for whatever length. public static String prefixZeros(String value, int len) { char[] t = new char[len]; int l = value.length(); int k = len-l; for(int i=0;i – Deian Feb 27 '15 at 20:30
  • 3
    @Mathu honestly that is not difficult to understand. Two strings are concatenated (joined together) and the first 5 characters are extracted from it. No magic. Not very sensible in this case (for fixed string Apple) but easy to understand. `("0000" + theString).substring(theString.length())` is more realistic. This pads `theString` with leading zeros. Sorry couldn't resist adding this comment :) – HankCa Apr 05 '16 at 03:01
  • @Dici It does "work" for a larger size, it just truncates your string to 8 characters .... So it depends on your expected behavior for longer-than-8-character strings (which wasn't specified by the OP) – Jan Oct 05 '16 at 16:20
  • 1
    This solution has a short syntax but it's not "crazy fast". If you're lucky the compiler will optimize it but essentially the real "fast" way to do this is using a `StringBuilder`, and it takes a loop to fill it. If the requirement is really to only truncate 8-characters strings that's ok, although that's a very narrow use-case, but this solution can never be called fast. It is just short. – Dici Oct 05 '16 at 19:32
  • Though it works, I wouldn't recommend using this way. It's not as clean as using String.format, which essentially is what you are trying to do: give a number a String format. By using this you need to read the statement twice to find out what it is doing. – Lluís Suñol Feb 05 '20 at 12:09
142
 StringUtils.leftPad(yourString, 8, '0');

This is from commons-lang. See javadoc

Yannjoel
  • 619
  • 2
  • 18
  • 31
Bozho
  • 554,002
  • 136
  • 1,025
  • 1,121
  • 3
    Why not use commons-lang? It has a loot of useful extras. – Bozho Oct 29 '10 at 12:45
  • 7
    Even if you are not able to use commons-lang, you can easily copy the source from StringUtils to make your own function. That would be a much better general solution than the selected answer. http://www.docjar.com/html/api/org/apache/commons/lang/StringUtils.java.html – kaliatech Oct 29 '10 at 13:01
  • 3
    what if that would be the only method the library is used for? Perhaps the added library is even many times bigger than the app it is used in. I can imagine quite some reasons *not* to add a commons library in an application. Don't get me wrong: I agree, it contains very useful stuff, but I understand the reluctance to stuff an app full of external JARs if the benefit is not needing to write just one (or a couple) of methods. – Bart Kiers Oct 29 '10 at 13:05
  • @kaliatech: yes, a much better GENERAL solution, but if he don't want to use the library probably a focused (short) solution is more appropriate. – Arne Deutsch Oct 29 '10 at 13:08
  • 2
    To answer the _"Why not use commons-lang? It has a loot of useful extras."_ question with a concrete example. Xiaomi ships an outdated version of commons-lang on its Android devices. Including a newer version in your app leads to classloader conflicts, so commons-lang can no longer be used in any Android project. – Nachi Oct 26 '16 at 10:33
  • 1
    @Nachi even if outdated StringUtils.leftPad should exist – Lluis Martinez May 31 '17 at 10:27
  • Updated Javadoc API links: [current stable release 3.9](http://commons.apache.org/proper/commons-lang/javadocs/api-3.9/org/apache/commons/lang3/StringUtils.html#leftPad-java.lang.String-int-char-), [legacy release 2.6](http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#leftPad(java.lang.String,%20int,%20char)) – Mikolasan Feb 04 '20 at 18:32
37

This is what he was really asking for I believe:

String.format("%0"+ (8 - "Apple".length() )+"d%s",0 ,"Apple"); 

output:

000Apple
  • Doesn't work for the general case; if you substitute "Apple" with a string of length 8 characters (which is possible in OP's case) this throws a `DuplicateFormatFlagsException` (because of the `00` in the format string). If you substitute a string longer than 8 characters, this throws an `IllegalFormatFlagsException` (because of the negative number). – nbrooks Oct 15 '16 at 08:47
  • You are right, but what about this then : `String.format("%0"+ (9 - "Apple".length() )+"d%s",0 ,"Apple").substring(0,8); `. Now you wont have this exception. – Abhinav Puri Jan 08 '17 at 07:25
  • 1
    Just wanna add `String.format("%0"+ (9 - "Apple".length() )+"d%s",0 ,"Apple").substring(0,8);` is WRONG, it should be `String.format("%0"+ (9 - "Apple".length() )+"d%s",0 ,"Apple").substring(1,9); `. –  Mar 09 '18 at 05:10
  • @user4231709 Great solution! +1 – user1697575 Jun 12 '20 at 17:46
29

You can use the String.format method as used in another answer to generate a string of 0's,

String.format("%0"+length+"d",0)

This can be applied to your problem by dynamically adjusting the number of leading 0's in a format string:

public String leadingZeros(String s, int length) {
     if (s.length() >= length) return s;
     else return String.format("%0" + (length-s.length()) + "d%s", 0, s);
}

It's still a messy solution, but has the advantage that you can specify the total length of the resulting string using an integer argument.

ChadyWady
  • 399
  • 3
  • 5
18

Using Guava's Strings utility class:

Strings.padStart("Apple", 8, '0');
Olivier Grégoire
  • 28,397
  • 21
  • 84
  • 121
15

You can use this:

org.apache.commons.lang.StringUtils.leftPad("Apple", 8, "0")
John Weisz
  • 23,615
  • 9
  • 74
  • 118
Bency Baby
  • 151
  • 1
  • 2
10

I've been in a similar situation and I used this; It is quite concise and you don't have to deal with length or another library.

String str = String.format("%8s","Apple");
str = str.replace(' ','0');

Simple and neat. String format returns " Apple" so after replacing space with zeros, it gives the desired result.

Erdi İzgi
  • 1,082
  • 1
  • 14
  • 29
  • Then you may want to split the string first, apply the operation above to the first split value, than concatenate the rest of the split values. – Erdi İzgi Mar 19 '18 at 10:52
6
String input = "Apple";
StringBuffer buf = new StringBuffer(input);

while (buf.length() < 8) {
  buf.insert(0, '0');
}

String output = buf.toString();
robert_x44
  • 8,904
  • 1
  • 30
  • 37
6

You can use:

String.format("%08d", "Apple");

It seems to be the simplest method and there is no need of any external library.

ungalcrys
  • 4,558
  • 2
  • 35
  • 22
  • String.format("%08d", anInteger); // this worked for me. String version throws exception – Bhdr Feb 16 '21 at 11:47
5

Use Apache Commons StringUtils.leftPad (or look at the code to make your own function).

kaliatech
  • 15,605
  • 4
  • 62
  • 76
2

In Java:

String zeroes="00000000";
String apple="apple";

String result=zeroes.substring(apple.length(),zeroes.length())+apple;

In Scala:

"Apple".foldLeft("00000000"){(ac,e)=>ac.tail+e}

You can also explore a way in Java 8 to do it using streams and reduce (similar to the way I did it with Scala). It's a bit different to all the other solutions and I particularly like it a lot.

Carlos
  • 333
  • 2
  • 7
1
public static void main(String[] args)
{
    String stringForTest = "Apple";
    int requiredLengthAfterPadding = 8;
    int inputStringLengh = stringForTest.length();
    int diff = requiredLengthAfterPadding - inputStringLengh;
    if (inputStringLengh < requiredLengthAfterPadding)
    {
        stringForTest = new String(new char[diff]).replace("\0", "0")+ stringForTest;
    }
    System.out.println(stringForTest);
}
Fathah Rehman P
  • 7,353
  • 3
  • 36
  • 41
1
public class PaddingLeft {
    public static void main(String[] args) {
        String input = "Apple";
        String result = "00000000" + input;
        int length = result.length();
        result = result.substring(length - 8, length);
        System.out.println(result);
    }
}
Arne Deutsch
  • 13,977
  • 4
  • 48
  • 72
1

You may have to take care of edgecase. This is a generic method.

public class Test {
    public static void main(String[] args){
        System.out.println(padCharacter("0",8,"hello"));
    }
    public static String padCharacter(String c, int num, String str){
        for(int i=0;i<=num-str.length()+1;i++){str = c+str;}
        return str;
    }
}
bragboy
  • 32,353
  • 29
  • 101
  • 167
1
public static String lpad(String str, int requiredLength, char padChar) {
    if (str.length() > requiredLength) {
        return str;
    } else {
        return new String(new char[requiredLength - str.length()]).replace('\0', padChar) + str;
    }
}
Nabil_H
  • 331
  • 3
  • 6
  • Whilst this code snippet is welcome, and may provide some help, it would be [greatly improved if it included an explanation](//meta.stackexchange.com/q/114762) of *how* it addresses the question. Without that, your answer has much less educational value - remember that you are answering the question for readers in the future, not just the person asking now! Please [edit] your answer to add explanation, and give an indication of what limitations and assumptions apply. – Toby Speight May 04 '17 at 17:30
1

Did anyone tried this pure Java solution (without SpringUtils):

//decimal to hex string 1=> 01, 10=>0A,..
String.format("%1$2s", Integer.toString(1,16) ).replace(" ","0");
//reply to original question, string with leading zeros. 
//first generates a 10 char long string with leading spaces, and then spaces are
//replaced by a zero string. 
String.format("%1$10s", "mystring" ).replace(" ","0");

Unfortunately this solution works only if you do not have blank spaces in a string.

Gico
  • 1,086
  • 1
  • 11
  • 28
1

Solution with method String::repeat (Java 11)

String str = "Apple";
String formatted = "0".repeat(8 - str.length()) + str;

If needed change 8 to another number or parameterize it

0

This is fast & works for whatever length.

public static String prefixZeros(String value, int len) {
    char[] t = new char[len];
    int l = value.length();
    int k = len-l;
    for(int i=0;i<k;i++) { t[i]='0'; }
    value.getChars(0, l, t, k);
    return new String(t);
}
Deian
  • 848
  • 9
  • 24
0

Can be faster then Chris Lercher answer when most of in String have exacly 8 char

int length = in.length();
return length == 8 ? in : ("00000000" + in).substring(length);

in my case on my machine 1/8 faster.

Community
  • 1
  • 1
Kuguar6
  • 26
  • 1
  • 5
0

Here is the simple API-less "readable script" version I use for pre-padding a string. (Simple, Readable, and Adjustable).

while(str.length() < desired_length)
  str = '0'+str;
Tezra
  • 7,096
  • 2
  • 19
  • 59
0

If you want to write the program in pure Java you can follow the below method or there are many String Utils to help you better with more advanced features.

Using a simple static method you can achieve this as below.

public static String addLeadingText(int length, String pad, String value) {
    String text = value;
    for (int x = 0; x < length - value.length(); x++) text = pad + text;
    return text;
}

You can use the above method addLeadingText(length, padding text, your text)

addLeadingText(8, "0", "Apple");

The output would be 000Apple

Googlian
  • 4,180
  • 3
  • 27
  • 29
-3

It isn't pretty, but it works. If you have access apache commons i would suggest that use that

if (val.length() < 8) {
  for (int i = 0; i < val - 8; i++) {
    val = "0" + val;
  }
}
mR_fr0g
  • 7,904
  • 5
  • 33
  • 51
  • 2
    The -1 is probably because this is a not so good example: you're using "magic numbers" and are concatenating Strings, something that should be replaced by using a StringBuilder or StringBuffer. – Bart Kiers Oct 29 '10 at 12:58