Reputation: 5203
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.
Upvotes: 0
Views: 198
Reputation: 1341
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.
Upvotes: 0
Reputation: 124215
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 $0
will replace matched part with itself plus space.
Upvotes: 2