javaarrayssplitintegerlpad

How to pad after split?


Help!

String all = "1.10.2";
String[] allArray = all.split("[.]");

What I want to do is make string "1.10.2" into 000010001000002 as integer. 00001 00010 00002 so giving padding and making each number into 5 digits and combining them as one integer. What should i do after split()?


Solution

  • You can do it with split like so:

    String[] allArray = all.split("\\.");
    for (int i = 0; i < allArray.length; ++i) {
      String padding = "0".repeat(5 - allArray[i].length());
      allArray[i] = padding + allArray[i];
    }
    String padded = String.join("", allArray);
    

    You can do it with streams like so:

    String padded = Arrays.stream(all.split("\\."))
        .map(s -> "0".repeat(5 - s.length()) + s)
        .collect(Collectors.joining(""));
    

    You can also do it without explicitly splitting, something like:

    String padded =
        Pattern.compile("(?:^|\\.)([^.]+)").matcher(all)
            .replaceAll(mr -> "0".repeat(5 - mr.group(1).length());