Umesh Awasthi
Umesh Awasthi

Reputation: 23587

Format a number based on the given format

I am trying to format a given mobile number to a given format.Number will be stored as a plain 10 digit number in the data base and to show it in the UI i need to format this number.

I am using JSTL to display this on the JSP side.I was planning to create a custom function which should accept the mobile number/phone number and the required format and will return the number in required format like

(xxx) xxx-xxx xxx-xxx-xxx

I was trying to split given phone number based on the regExp but not very sure how to do this

String phoneNumber="1232345678";
Pattern pattern=Pattern.compile("\\d{3}\\d{3}\\d{4}");
String [] s=pattern.split(phoneNumber);

Another way to split given string and den can use concatenation produce a desired format.

What can be the best way to achieve this

Upvotes: 1

Views: 1491

Answers (2)

Bohemian
Bohemian

Reputation: 424993

You need only one line:

String output = phoneNumber.replaceAll("(\\d{3})(\\d{3})(\\d{4})", "($1) $2-$3");

This code produces the following effect:

1232345678 --> (123) 234-5678


The moral here is:

  • Use the API (rather than writing your own code)
  • Don't over-complicate things (when a simple approach is available, use it)

Upvotes: 2

user1766873
user1766873

Reputation:

Take a look at brute force solution:

Simply put a format in such as, "(xxx) xxx-xxxx", and the code will replace x with numbers from the phone number.

public static String format(String number, String format) {
    char[] arr = new char[format.length()];
    int i = 0;
    for (int j = 0; j < format.length(); j++) {
        if (format.charAt(j) == 'x')
            arr[j] = number.charAt(i++);
        else
            arr[j] = format.charAt(j);
    }

    return new String(arr);
}

Upvotes: 0

Related Questions