What is the way to insert a colon(:) after every two characters in a string?

I am trying to figure out that -

INPUT: String data = "506313B5EA3E";

OUTPUT: String data = "50:63:13:B5:EA:3E";

I tried using-

java.util.Arrays.toString(data.split("(?<=\\G..)"))

But the output is: [50, 6313B5EA3E]

Jon Skeet
people
quotationmark

Two simple options involving loops, both assuming you have already checked that the input is non-empty and has an even number of characters:

Use StringBuilder

StringBuilder builder = new StringBuilder(data.length() * 3 / 2 - 1);
for (int i = 0; i < data.length(); i += 2) {
    if (i != 0) {
        builder.append(":");
    }
    builder.append(data.substring(i, i + 2));
}
String text = builder.toString();

Use a char array

char[] output = new char[data.length() * 3 / 2 - 1];
int outputIndex = 0;
for (int i = 0; i < data.length(); i += 2) {
    if (i != 0) {
        output[outputIndex++] = ':';
    }
    output[outputIndex++] = data.charAt(i);
    output[outputIndex++] = data.charAt(i + 1);
}
String text = new String(output);

Another option would be to use Joiner from Guava along with your previous split:

String text = Joiner.on(':').join(data.split("(?<=\\G..)"));

people

See more on this question at Stackoverflow