I have a string as follows
String str = "AUTHOR01BOOK"
In this string I want to add this number 00001
. How can I do that?
I tried concatenate it but the output I got is AUTHOR01BOOK1
. My code is not appending zeros. How can I do that?
I have a string as follows
String str = "AUTHOR01BOOK"
In this string I want to add this number 00001
. How can I do that?
I tried concatenate it but the output I got is AUTHOR01BOOK1
. My code is not appending zeros. How can I do that?
You can use the print format.
String str="AUTHOR01BOOK";
int num = 000001;
System.out.printf("%s%06d", str, num);
or use the String.format function to store it in a variable:
String myConcat = String.format("%s%05d", str, num);
EDIT: To answer raju's follow up question about doing this in a loop, Create a method that will return the formatted string:
static String myConcatWithLoop(String str, int iteration){
return String.format("%s%05d", str, iteration);
}
then call this in your loop:
for (int i = 1; i <= 100; i++) {
System.out.println(myConcatWithLoop(str, i));
}
if you store '000001' in int datatype it will treat as an octal. That is
int a=000001; System.out.println(a); Output: 1 It will treat it as OCTAL number
So you cannot store a number beginning with 0 in int as compiler will typecast it. Therefore for that you have to work with Strings only :)
Please try the below code. It not only displays but also changes the string. StringUtils help us to pad the left zeros. Number 4 in the leftPad method denotes the number of zeros. Its not a dynamic solution but it fulfills your need.
import org.apache.commons.lang.StringUtils;
public class Interge {
public static void main(String[] args) {
int i =00001;
String s= i+"";
String result = StringUtils.leftPad(s, 4, "0");
String fnlReslt = "AUTHOR01BOOK"+result;
System.out.println("The String : " + fnlReslt);
}
}
Another approach is use StringBuilder
public class JavaApplication {
public static void main(String[] args) {
JavaApplication ex = new JavaApplication();
String str = "AUTHOR01BOOK";
System.out.println(ex.paddingZero(str));
}
public String paddingZero(String str) {
StringBuilder sb = new StringBuilder();
sb.append(str);
sb.append("00001");
return sb.toString();
}
}