Adding number with zero in left pad

时间:2016-04-04 17:30:41

标签: java loops padding increment

First of all Sorry for foolish question As i am new to java. actually i have a string which contains a number in between i want to increment its value up to some specific number. i am very confused how to explain . below is the example what i need to do.

I have a string i.e :-
"03000001da00000001666666"
and i want to increase its value like below

"03000001da00000002666666"
"03000001da00000003666666"
"03000001da00000004666666" etc.

I wrote a simple java code below:

but its print wrongly i.e:-
"03000001da2666666"
"03000001da3666666"
"03000001da4666666" etc.

public class Demo {

public static void main(String[] args) {
        String content = "03000001da00000001666666";

        String firstIndex = content.substring(0, 10);
        String requireIndex = content.substring(10,18);
        String lastIndex  = content.substring(18, content.length());
       for(int i = 0; i <= 10;i++){
           System.out.println(firstIndex + (Integer.parseInt(requireIndex)+i) + lastIndex);
       }
    } 
}

need some help please help me.

2 个答案:

答案 0 :(得分:1)

You can use printf and a format String (like %08d) to pad your int at 8 characters with leading zeros. You can also parse your int once before you loop and String.substring(int) (with only one parameter) reads the rest of the String by default. That might look something like,

String content = "03000001da00000001666666";
String firstIndex = content.substring(0, 10);
String lastIndex = content.substring(18);
int middle = Integer.parseInt(content.substring(10, 18));
for (int i = 0; i <= 10; i++) {
    System.out.printf("%s%08d%s%n", firstIndex, middle + i, lastIndex);
}

答案 1 :(得分:1)

Try this:

public static void main(String[] args) {
    String content = "03000001da00000001666666";

    String firstIndex = content.substring(0, 10);
    String requireIndex = content.substring(10,18);
    String lastIndex  = content.substring(18);
    for(int i = 0; i <= 10;i++){
        System.out.printf("%s%08d%s%n",firstIndex, Integer.parseInt(requireIndex)+i, lastIndex);
    }
}