-3

Hey everyone just wondering how I would go about splitting a number such as:

"1100000000000001"

to:

"11.00.00.00.00.00.00.01"

Possibly using regex?

a.maz
  • 9
  • 2
  • Regex is for finding patterns within a string. In this case, you're not looking for any pattern, you just want to put a dot every 2 characters. This sounds like a great job for [`String#substring()`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#substring(int,int)). – Charlie Armstrong Oct 08 '20 at 16:23
  • Thank you! I will definitely try that out! – a.maz Oct 08 '20 at 16:38
  • Also, an exact dupe of https://stackoverflow.com/questions/3760152/split-string-to-equal-length-substrings-in-java – Wiktor Stribiżew Oct 08 '20 at 20:48

3 Answers3

1

Using a regex is not the best solution for this problem. Constructing the string yourself offers a simple way to do this:

String str = "1234567890";
String newStr = "";
for(int i = 0; i < str.length(); i++) {
    newStr += str.charAt(i);
    if(i % 2 != 0 && i != str.length() - 1) {
        newStr += ".";
    }
}
System.out.println(newStr);
Pieter12345
  • 1,713
  • 1
  • 11
  • 18
0

Split at every second char and join the elements of the resulting array using . as a delimeter:

String reg = "(?<=\\G..)";
String str = "1100000000000001";
String res = Pattern.compile(reg).splitAsStream(str).collect(Collectors.joining("."));
System.out.println(res);
Eritrean
  • 15,851
  • 3
  • 22
  • 28
0

using regex pattern :

String str = "1100000000000001";
String pattern = "(\\d\\d)(?!$)";
System.out.println(str.replaceAll(pattern, "$1."));
aziz k'h
  • 775
  • 6
  • 11