我想弄明白 -
INPUT: String data = "506313B5EA3E";
输出: String data = "50:63:13:B5:EA:3E";
我尝试使用 -
java.util.Arrays.toString(data.split("(?<=\\G..)"))
但输出是:[50, 6313B5EA3E]
答案 0 :(得分:17)
您可以使用RegExp:
String input = "0123456789abcdef";
String output = input.replaceAll("..(?!$)", "$0:")
// output = "01:23:45:67:89:ab:cd:ef"
答案 1 :(得分:5)
两个涉及循环的简单选项,假设您已经检查过输入是非空的并且具有偶数个字符:
使用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();
使用字符数组
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);
String text = Joiner.on(':').join(data.split("(?<=\\G..)"));