Android Phone Number Format formatPhoneNumber(String phoneNumber)

Here you can find the source of formatPhoneNumber(String phoneNumber)

Description

Format plain phone number into a formatted string

Parameter

Parameter Description
phoneNumber a parameter

Declaration

public static String formatPhoneNumber(String phoneNumber) 

Method Source Code

//package com.java2s;

public class Main {
    /**//ww  w. j  a  v  a  2s  .c  o m
     * Format plain phone number into a formatted string
     * @param phoneNumber
     */
    public static String formatPhoneNumber(String phoneNumber) {
        if (phoneNumber == null || phoneNumber.isEmpty()
                || phoneNumber.length() < 10) {
            return phoneNumber;
        }

        char[] chars = phoneNumber.toCharArray();
        StringBuilder sb = new StringBuilder();

        if (chars.length == 10) {
            sb.append("(" + chars[0]);
            sb.append(chars[1]);
            sb.append(chars[2]);
            sb.append(")-");
            sb.append(chars[3]);
            sb.append(chars[4]);
            sb.append(chars[5]);
            sb.append("-");
            sb.append(chars[6]);
            sb.append(chars[7]);
            sb.append(chars[8]);
            sb.append(chars[9]);

            return sb.toString();

        } else if (chars.length == 11) {
            sb.append("(" + chars[1]);
            sb.append(chars[2]);
            sb.append(chars[3]);
            sb.append(")-");
            sb.append(chars[4]);
            sb.append(chars[5]);
            sb.append(chars[6]);
            sb.append("-");
            sb.append(chars[7]);
            sb.append(chars[8]);
            sb.append(chars[9]);
            sb.append(chars[10]);

            return sb.toString();
        }

        return phoneNumber;
    }
}

Related

  1. formatPhoneNumber(String number)
  2. formatPhoneNumber(String numberString)
  3. formatPhone(String phone)
  4. formatPhone(String phone, String format)