I need to insert a space after every character of a string.
i.e.
String name = "Joe";
should become: "J o e"
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.
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('').
You can use the regular expression '..' to match each two characters and replace it with "$0 " to add the space: s = s. replaceAll("..", "$0 ");
Shorter would be using a regex:
System.out.println("Joe".replaceAll(".(?!$)", "$0 "));
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