Adding space between characters

//Where n = no of character after you want space

int n =2;
StringBuilder str = new StringBuilder("ABCDEFGHIJKLMNOP");
int idx = str.length() - n;
while (idx > 0){
   str.insert(idx, " ");
   idx = idx - n;
}
return str.toString();

Explanation, this code will add space from right to left:

str = "ABCDEFGH" int idx = total length - 2; //8-2=6
while (8>0)
{
    str.insert(idx, " "); //this will insert space at 6th position
    idx = idx - n; // then decrement 6-2=4 and run loop again
} 

The final output will be

AB CD EF GH

You can use the regular expression '..' to match each two characters and replace it with "$0 " to add the space:

s = s.replaceAll("..", "$0 ");

You may also want to trim the result to remove the extra space at the end.

See it working online: ideone.

Alternatively you can add a negative lookahead assertion to avoid adding the space at the end of the string:

s = s.replaceAll("..(?!$)", "$0 ");

Tags:

Java

String

Space