Adding space between characters

Babu R picture Babu R · Jun 22, 2012 · Viewed 25.3k times · Source

I want to add space after every two chars in a string.

For example:

javastring 

I want to turn this into:

ja va st ri ng

How can I achieve this?

Answer

Mark Byers picture Mark Byers · Jun 22, 2012

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 ");