Reputation: 1035
I want to add space after every two chars in a string.
For example:
javastring
I want to turn this into:
ja va st ri ng
How can I achieve this?
Upvotes: 9
Views: 38916
Reputation: 67
//Where n = no of character after you want space
int n =2;
StringBuilder str = new StringBuilder("ABCDEFGHIJKLMNOP");
int idx = str.length() - n;
while (idx > 0){
str.insert(idx, " ");
idx = idx - n;
}
return str.toString();
Explanation, this code will add space from right to left:
str = "ABCDEFGH" int idx = total length - 2; //8-2=6
while (8>0)
{
str.insert(idx, " "); //this will insert space at 6th position
idx = idx - n; // then decrement 6-2=4 and run loop again
}
The final output will be
AB CD EF GH
Upvotes: 5
Reputation: 8604
I wrote a generic solution for this...
public static String insertCharacterForEveryNDistance(int distance, String original, char c){
StringBuilder sb = new StringBuilder();
char[] charArrayOfOriginal = original.toCharArray();
for(int ch = 0 ; ch < charArrayOfOriginal.length ; ch++){
if(ch % distance == 0)
sb.append(c).append(charArrayOfOriginal[ch]);
else
sb.append(charArrayOfOriginal[ch]);
}
return sb.toString();
}
Then call it like this...
String result = InsertSpaces.insertCharacterForEveryNDistance(2, "javastring", ' ');
System.out.println(result);
Upvotes: 1
Reputation: 839234
You can use the regular expression '..'
to match each two characters and replace it with "$0 "
to add the space:
s = s.replaceAll("..", "$0 ");
You may also want to trim the result to remove the extra space at the end.
See it working online: ideone.
Alternatively you can add a negative lookahead assertion to avoid adding the space at the end of the string:
s = s.replaceAll("..(?!$)", "$0 ");
Upvotes: 49