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 ofinput
(?!
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.