I need to insert a space after every character of a string.
i.e.
String name = \"Joe\";
should become: \"J o e\"
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 stringWithSpaceAfterEvery4Chars = stringWith16Chars?.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:
stringWith16Chars = "123456789012"
and the output would be,
stringWithSpaceAfterEvery4Chars = "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());
Using kotlin
val textToBeDevided = "123456789"
textToBeDevided
.subSequence(1, textToBeDevided.length)
.chunked(3) // group every 3 chars
.joinToString(" ") // merge them applying space
You can convert Joe to char[] by using String's toCharArray() then traverse char[] to grab the char into another char[] and as you add the char to the second char[], you add a space character '" "'. Set a if-else within the loop to detect the last character so that you wouldn't add a space character by accident behind the last character. Use a String to valueOf() the resulting char[] to turn it into a String object.
Removing the final space:
String joe = "Joe";
StringBuilder sb = new StringBuilder();
String sep = "";
for (char c: joe.toCharArray()) {
sb.append(sep).append(c);
sep = " ";
}
System.out.println(sb.toString());