0

I have the following string:

String x = "020120765";

I want this string in the form of 02 0120765. One possibility is:

x = x.substring(0,2) + " " + x.substring(2, x.length());

or:

x = String.format("%s %s", x.substring(0, 2), x.substring(2));

Is there any other better or elegant way? I'm thinking in the direction of regex. I have tried the following:

x = String.format("%s %s", x.split("\\d{2}"));

But it doesn't work.

1
  • 1
    You can omit x.length() as the second argument to substring, and just write x.substring(2) Commented Apr 24, 2014 at 12:05

5 Answers 5

8

You could also use a StringBuilder with its insert method:

x = new StringBuilder(x).insert(2, ' ').toString();
Sign up to request clarification or add additional context in comments.

2 Comments

+1 it seems like the easiest and most straightforward solution.
+1. The position changes, so I only need to insert space if it matches the regex. Otherwise the default string should be the value.
5

Another option

x = x.replaceAll("(..)(.+)", "$1 $2");

1 Comment

Good one. I changed to: x.replaceFirst("(\\d{2})(\\d+)","$1 $2"). How could I not see that. Thanks.
2

If you are interested in regex solution then you can try with

x = x.replaceAll("^..", "$0 ")

^.. will match first first two characters. $0 is reference to match from group 0 (which contains entire match) so $0will replace matched part with itself plus space.

1 Comment

This seems to me to be the most straightforward way to attack this problem.
0
x=String.format("%s %s",x.split("(?<=\\G.{2})", 2))

will not work because you are trying to pass an array in and you have too few arguments. You could, however, do it like this:

x=String.format("%s %s",x.split("(?<=\\G.{2})", 2)[0], x.split("(?<=\\G.{2})", 2)[1]);

Or, more neatly,

String[] arr = x.split("(?<=\\G.{2})", 2);
x = String.format("%s %s", arr[0], arr[1]);

EDIT: I am very inexperienced with regex so please excuse the previous incorrect regex patterns.

3 Comments

I am not the downvoter but split("\\d{2}") will remove part matched by \\d{2} which doesn't seem to be what OP wants.
I made the mistake of copying the OP's regex. Give me a few minutes and I will fix it
Please see the edit. The regex patterns are now correct and have been tested =)
0
x.replaceAll("(?<=^..)", " ");

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.