How to insert Space after every Character of an existing String in Java?
This will space out all letters in each word and not between words
"Joe Black".replaceAll("\\B", " ") -> "J o e B l a c k"
This will put space for each character (including original spaces)
"Joe Black".replaceAll("\\B|\\b", " ") -> " J o e B l a c k "
Shorter would be using a regex:
System.out.println("Joe".replaceAll(".(?!$)", "$0 "));
For Android & Kotlin users, if you want to add space after every X characters then use this
val stringWithSpaceAfterEvery4thChar = stringWith12Chars?.replace("....".toRegex(), "$0 ")
Here I added 4 dots in method to add space after every 4th character in my whole string. If you want space after every 2 characters then add only 2 dots in the method.
My variables:
stringWith12Chars = "123456789012"
and the output would be,
stringWithSpaceAfterEvery4thChar = "1234 5678 9012"
Something like:
String joe = "Joe";
StringBuilder sb = new StringBuilder();
for (char c: joe.toCharArray()) {
sb.append(c).append(" ");
}
System.out.println(sb.toString().trim());