user3111525
user3111525

Reputation: 5203

Java how to format a string?

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

Answers (5)

Dawood ibn Kareem
Dawood ibn Kareem

Reputation: 79807

x.replaceAll("(?<=^..)", " ");

Upvotes: 0

DerStrom8
DerStrom8

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

Pshemo
Pshemo

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 $0will replace matched part with itself plus space.

Upvotes: 2

Alexis C.
Alexis C.

Reputation: 93842

You could also use a StringBuilder with its insert method:

x = new StringBuilder(x).insert(2, ' ').toString();

Upvotes: 8

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 135992

Another option

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

Upvotes: 5

Related Questions