Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding space between characters

Tags:

java

string

space

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?

like image 648
Babu R Avatar asked Jun 22 '12 02:06

Babu R


People also ask

What's the space between characters called?

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.

How do you put a space between characters in a string?

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(' ') .


2 Answers

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 ");
like image 184
Mark Byers Avatar answered Sep 21 '22 10:09

Mark Byers


//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
like image 42
Nitin Divate Avatar answered Sep 20 '22 10:09

Nitin Divate