-5

I have a string like

String[] toppings = {"1234", "56789", "123456"};

for each element of toppings I need to check the length, and if it is less than 9, I need to add zeros at the end.

for example consider first element of the array, it is 1234. Its length is 4, so I need to add 5 zeros at the end which looks like "123400000".

similarly I need to do it for all the elements present in toppings.

And finally at the end I need to concat all the vales present in toppings to one string. Means my output must look like String x = "123400000567890000123456000".

Any suggestions?

Thanks,

technophile
  • 17
  • 1
  • 7

3 Answers3

2

Loop over all the items, right pad then print them. In Java 8:

toppings.stream.map(s -> String.format("%-09d", s)).collect(Collectors.joining());

//        ^                        ^                                ^
// Use the stream API       Right-pad with 0       Munge them all into a single string.
Paul Hicks
  • 11,495
  • 3
  • 41
  • 67
  • Thanks for your answer, it worked fine for me. I have no Idea on lamda operators, by seeing your post I got some knowledge on how to use them. Thank you very much – technophile Jun 01 '16 at 03:11
1

Try this.

String x = Arrays.stream(toppings)
    .map(s -> String.format("%-9s", s))
    .collect(Collectors.joining())
    .replaceAll(" ", "0");
saka1029
  • 13,523
  • 2
  • 13
  • 37
0

You can get the length using .length() and from there just add "0" to the string until it reaches 9.

String[] toppings = {"1234", "56789", "123456"};

for (int q = 0; q < toppings.length; q++){

    int length = toppings[q].length(); // # of digits
    int maxlength = 9;

    if (length<maxlength){ // only do this if it is below 9
        for (int i = length; i < maxlength; i++){ // go through and add 0's
            toppings[q] = toppings[q] + "0";
        }
    }
}

String mix = "";
for (int q = 0; q < toppings.length; q++){ // add all the strings to one single string
    mix+=toppings[q];
}

System.out.println(mix);

Returns:

123400000567890000123456000
Arthur
  • 1,246
  • 1
  • 11
  • 18