9

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?

2
  • 1
    possible duplicate :stackoverflow.com/questions/4469984/… Commented Jun 22, 2012 at 2:07
  • Loop the string variable with for or while instructions and after two characters print a space! Commented Jun 22, 2012 at 2:09

3 Answers 3

49

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 ");
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, you just saved me from implementing the loop.
5

//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

1 Comment

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 } final output will be AB CD EF GH Hope this explaination helps
1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.