Reputation: 5554
I have a situation in which I need to display a string with some spaces in the UI. This is for better readability.
For example if my data is "1234567890", I want to display it as "123 456 7890". I was wondering if this can be done using Java's String format methods?
Upvotes: 2
Views: 668
Reputation: 1921
I'd do it with replaceAll.
String test = "1112223333";
System.out.println(test.replaceAll("(.{3})(.{3})(.{4})", "$1 $2 $3"));
This uses the regular expression (.{3})(.{3})(.{4})
the .{x}
matches anything. the {x}
is the number of times. I surround it in parenthesis (.{3})
to capture the string that matches in $1, $2 and $3.
So $1 = "111", $2 = "222" and $3 = "3333"
Upvotes: 1
Reputation: 5183
yes you can do it with String.format() First you can split the string in an array to have
a[0]="123"
a[1]="456"
a[2]="7890"
then use the following
String.format("%1$3s %2$3s %3$3s",a );
Upvotes: 0
Reputation: 64125
It looks like you are trying to format a phone number? You could use DecimalFormat
, define the message format and make a String[]
with sub strings of the original string.
Upvotes: 0
Reputation: 3011
No, you'd have to implement your own code. See here for the String API.
Upvotes: 1