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?
Hence, the space between characters is called Kerning. It is the space between individual characters. Also, most fonts come with a default kerning, and there is a limit to adjusting the space between the characters.
To add a space between the characters of a string, call the split() method on the string to get an array of characters, and call the join() method on the array to join the substrings with a space separator, e.g. str. split(''). join(' ') .
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 ");
//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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With