I have to split this string:
00016282000079116050
It has predefined chunks. Should be just like that:
00016 282 00 0079 116 050
I made this code:
String unformatted = String.valueOf("00016282000079116050");
String str1 = unformatted.substring(0,5);
String str2 = unformatted.substring(5,8);
String str3 = unformatted.substring(8,10);
String str4 = unformatted.substring(10,14);
String str5 = unformatted.substring(14,17);
String str6 = unformatted.substring(17,20);
System.out.println(String.format("%s %s %s %s %s %s", str1, str2, str3, str4, str5, str6));
It works, but I need to make this code more presentable/prettier.
Something with Java 8 streams or regex should be good. Any suggestions?
You could use a regular expression to compile a Pattern
with 6 groups, something like
String unformatted = "00016282000079116050"; // <-- no need for String.valueOf
Pattern p = Pattern.compile("(\\d{5})(\\d{3})(\\d{2})(\\d{4})(\\d{3})(\\d{3})");
Matcher m = p.matcher(unformatted);
if (m.matches()) {
System.out.printf("%s %s %s %s %s %s", m.group(1), m.group(2), m.group(3),
m.group(4), m.group(5), m.group(6));
}
Outputs (as requested)
00016 282 00 0079 116 050
Or, as pointed out in the comments, you could use Matcher.replaceAll(String)
like
if (m.matches()) {
System.out.println(m.replaceAll("$1 $2 $3 $4 $5 $6"));
}
A more java oriented way would be to use a loop and an array of predefined lengths.
int[] lims = {5,3,2,4,3,3};
int total = 0;
String original = "00016282000079116050";
for (int i = 0 ; i < lims.length ; i++) {
System.out.print(original.substring(total, total+=lims[i]) + " ");
}
00016 282 00 0079 116 050
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With