0

Is there a way in java 8(or lower) that formats a single string putting the character ':' between each 2 characters? The simpler, the best.

Example (or something similar to this):

String a = "000000";

string b = someMethodThatIdontKnow(a, 2, ':'); // b -> 00:00:00

Ps: I know how to do this using split method or StringBuilder, but I want a cleaner way to do the work.

Pss: Consider that the input string is ever going to have length 6

OneNoOne
  • 587
  • 7
  • 23
  • You can use regexp with `String.replaceAll` check [this answer](https://stackoverflow.com/a/537185/916225) – seenukarthi Mar 03 '20 at 12:21
  • 2
    A method that insterts a : for every 2 characters doesn't seem like a common use case. Most methods would be targeted to a specific use case like parsing and formatting timestamps and such. For a timestamp you shouldn't blindly insert : but parse and format the String using DateTimeFormatter. – Nicktar Mar 03 '20 at 12:26
  • I can't understand way this question was closed. I think It was a misunderstood choice. – OneNoOne Mar 12 '20 at 20:48

4 Answers4

1

You can use following regex to achieve it:

(.{2})

try this:

public String someMethodThatIdontKnow(String s, int length, String r){
    return s.replaceAll("(.{"+length+"})", "$1"+r);
}
Mustahsan
  • 3,852
  • 1
  • 18
  • 34
0

I think this is will help:

public static String someMethodThatIdontKnow(String a,int noOfDigits,String splitBy){
    String newA = a.replaceAll("\\d{"+noOfDigits+"}", "$0"+splitBy);
    return newA.substring(0,newA.length()-1);
}
AMA
  • 408
  • 3
  • 9
0

May be try this:

StringBuilder str = new StringBuilder(data.length());
for (int i = 0; i < data.length(); i = i+ 2) {
    if (i != 0) {
        str.append(":");
    }
    str.append(data.substring(i, i + 2));
}
String text = builder.toString();
joy08
  • 9,004
  • 8
  • 38
  • 73
0

String#join in combination with String.split for Java 8+

String str = "000000";
String res = String.join(":", str.split("(?<=\\G..)"));
System.out.println(res);
Eritrean
  • 15,851
  • 3
  • 22
  • 28