PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, July 21, 2022

[FIXED] How to pad after split?

 July 21, 2022     arrays, integer, java, lpad, split     No comments   

Issue

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


Answered By - Andy Turner
Answer Checked By - Pedro (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing