Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert Space after every Character of an existing String in Java?

Tags:

I need to insert a space after every character of a string.

i.e. String name = "Joe";

should become: "J o e"

like image 467
Philipp Redeker Avatar asked Dec 17 '10 11:12

Philipp Redeker


People also ask

How do you give a space in a string in Java?

Use the String. format() method to pad the string with spaces on left and right, and then replace these spaces with the given character using String. replace() method. For left padding, the syntax to use the String.

How do I add 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 give a space between two 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 ");


1 Answers

Shorter would be using a regex:

System.out.println("Joe".replaceAll(".(?!$)", "$0 "));
like image 72
Peter Kofler Avatar answered Nov 13 '22 07:11

Peter Kofler