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?
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);
}
}
%07s instead of %07d, you will get a FormatFlagsConversionMismatchException. you can try it.int number = "Apple"; didn't work! How odd? 🤔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.)
("0000" + theString).substring(theString.length()) is more realistic. This pads theString with leading zeros. Sorry couldn't resist adding this comment :)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. StringUtils.leftPad(yourString, 8, '0');
This is from commons-lang. See javadoc
This is what he was really asking for I believe:
String.format("%0"+ (8 - "Apple".length() )+"d%s",0 ,"Apple");
output:
000Apple
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).String.format("%0"+ (9 - "Apple".length() )+"d%s",0 ,"Apple").substring(0,8); . Now you wont have this exception.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.
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.
String str = String.format("%8s","Apple").replace(' ', '0');Use Apache Commons StringUtils.leftPad (or look at the code to make your own function).
Copied Source:
/**
* Left pad a String with a specified String.
*
* <p>Pad to a size of {@code size}.</p>
*
* <pre>
* StringUtils.leftPad(null, *, *) = null
* StringUtils.leftPad("", 3, "z") = "zzz"
* StringUtils.leftPad("bat", 3, "yz") = "bat"
* StringUtils.leftPad("bat", 5, "yz") = "yzbat"
* StringUtils.leftPad("bat", 8, "yz") = "yzyzybat"
* StringUtils.leftPad("bat", 1, "yz") = "bat"
* StringUtils.leftPad("bat", -1, "yz") = "bat"
* StringUtils.leftPad("bat", 5, null) = " bat"
* StringUtils.leftPad("bat", 5, "") = " bat"
* </pre>
*
* @param str the String to pad out, may be null
* @param size the size to pad to
* @param padStr the String to pad with, null or empty treated as single space
* @return left padded String or original String if no padding is necessary,
* {@code null} if null String input
*/
public static String leftPad(final String str, final int size, String padStr) {
if (str == null) {
return null;
}
if (isEmpty(padStr)) {
padStr = SPACE;
}
final int padLen = padStr.length();
final int strLen = str.length();
final int pads = size - strLen;
if (pads <= 0) {
return str; // returns original String when possible
}
if (padLen == 1 && pads <= PAD_LIMIT) {
return leftPad(str, size, padStr.charAt(0));
}
if (pads == padLen) {
return padStr.concat(str);
}
if (pads < padLen) {
return padStr.substring(0, pads).concat(str);
}
final char[] padding = new char[pads];
final char[] padChars = padStr.toCharArray();
for (int i = 0; i < pads; i++) {
padding[i] = padChars[i % padLen];
}
return new String(padding).concat(str);
}
You can use:
String.format("%08d", "Apple");
It seems to be the simplest method and there is no need of any external library.
I like the solution from Pad a String with Zeros
String.format("%1$" + length + "s", inputString).replace(' ', '0');
with length = "8" and inputString = "Apple"
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.
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;
}
}
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);
}
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;
}
}
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.
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.
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
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;
}
}
val - 8 isn't correct logic for the Java and will cause compile error