Adding number with zero in left pad

蹲街弑〆低调 提交于 2019-12-12 03:27:59

问题


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.


回答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);
    }
}



回答2:


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);
}


来源:https://stackoverflow.com/questions/36409136/adding-number-with-zero-in-left-pad

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!