我要把手机号码中间4位显示成星号(*)该如何做

解决方案 »

  1.   

    String.subString.replace 比较笨
      

  2.   


    String phone = "13820080808";
    char[] ch = phone.toCharArray();
    for (int i = 3; i < 7; i++) {
      ch[i] = '*';
    }
    phone = new String(ch);
    System.out.println(phone);
      

  3.   

    String phone2 = "15110097960";
    System.out.println(phone2.substring(0,3) + "****" + phone2.substring(7, phone2.length()));
      

  4.   

    public class Test {    public static void main(String[] args) {
            String str = "13800138000";
            for(int i = -20; i < 20; i++) {
                System.out.println(i + " --> " + asteriskHidden(str, i));
            }
        }
        
        public static String asteriskHidden(String str, int count) {
            return hidden(str, count, '*');
        }
        
        public static String hidden(String str, int count, char replacement) {        
            if(str == null || count < 1) {
                return str;
            }
            char[] chs = str.toCharArray();
            int offset = 0;
            if(chs.length - count > 0) {
                offset = (chs.length - count) / 2;
            }
            int end = Math.min(offset + count, chs.length);
            while(offset < end) {
                chs[offset++] = '*';
            }
            return new String(chs);
        }
    }