Question

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]

Was it helpful?

Solution

You can use a RegExp:

String input = "0123456789abcdef";
String output = input.replaceAll("..(?!$)", "$0:")
// output = "01:23:45:67:89:ab:cd:ef"

How does it work?

  • .. matches exactly two characters. (?!$) ensures that these two characters are not at the end of input (?! is a negative lookahead, $ stands for the end).
  • The matching two characters will now be replaced by themselves ($0 means the whole matching string) and the colon we want.
  • Since we are using replaceALL, this operation repeats for every two-character group. Remember: except the last one.

OTHER TIPS

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..)"));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top