Android Phone Number Format formatPhone(String phone, String format)

Here you can find the source of formatPhone(String phone, String format)

Description

format Phone

Declaration

public static String formatPhone(String phone, String format) 

Method Source Code

//package com.java2s;

public class Main {
    public static String formatPhone(String phone) {
        return formatPhone(phone, null);
    }//from  ww  w  .jav  a 2 s . c  om

    public static String formatPhone(String phone, String format) {
        if (isNullOrEmpty(phone)) {
            return phone;
        }

        String s = "";
        char[] cs = getDigit(phone).toCharArray();
        int i = 0;

        if (isNullOrEmpty(format)) {
            if (cs[0] == '1') {
                format = "1 (ddd) ddd-dddd";
                i++;
            } else {
                format = "(ddd) ddd-dddd";
            }
        }

        for (char c : format.toCharArray()) {
            if (c == 'd') {
                s += cs[i++];

                if (i > cs.length - 1) {
                    break;
                }
            } else {
                s += c;
            }
        }

        return s;
    }

    public static boolean isNullOrEmpty(String input) {
        if (input == null) {
            return true;
        }

        return input.trim().isEmpty();
    }

    public static String getDigit(String input) {
        if (isNullOrEmpty(input)) {
            return input;
        }

        String s = "";
        for (char c : input.toCharArray()) {
            if (c >= '0' && c <= '9') {
                s += c;
            }
        }

        return s;
    }
}

Related

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