Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add spaces between the characters of a string in Java?

Tags:

java

string

I just want to add a space between each character of a string. Can anyone help me figuring out how to do this?

E.g. given "JAYARAM", I need "J A Y A R A M" as the result.

like image 900
Jey Avatar asked Aug 25 '11 11:08

Jey


People also ask

How do I add a space between characters in Java?

You can use the regular expression '..' to match each two characters and replace it with "$0 " to add the space: s = s. replaceAll("..", "$0 ");

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

How do you add a space in a character?

Select the text that you want to change. On the Home tab, click the Font Dialog Box Launcher, and then click the Advanced tab. Note: If you're using Word 2007 the tab is called Character Spacing. In the Spacing box, click Expanded or Condensed, and then specify how much space you want in the By box.


1 Answers

Unless you want to loop through the string and do it "manually" you could solve it like this:

yourString.replace("", " ").trim() 

This replaces all "empty substrings" with a space, and then trims off the leading / trailing spaces.

ideone.com demonstration


An alternative solution using regular expressions:

yourString.replaceAll(".(?=.)", "$0 ") 

Basically it says "Replace all characters (except the last one) with with the character itself followed by a space".

ideone.com demonstration

Documentation of...

  • String.replaceAll (including the $0 syntax)
  • The positive look ahead (i.e., the (?=.) syntax)
like image 157
aioobe Avatar answered Oct 06 '22 04:10

aioobe