java實現姓名、手機號和銀行卡中間用*號代替
阿新 • • 發佈:2019-02-12
package com.util.date; /** * @Description 模擬各大網站充值時的資料顯示 * @author ShengLiu * @date 2018/7/4 */ public class TestUtil { /** * 定義所有常量 */ public static final String EMPTY = ""; public static final int ZERO = 0; public static final int ONE = 1; public static final int TWO = 2; public static final int THREE = 3; public static final int FOUR = 4; /** * @Description 字串向左擷取 * @author ShengLiu * @date 2018/7/4 * @param str * @param len * @return java.lang.String */ public static String left(String str, int len) { if (str == null) { return null; } if (len < ZERO) { return EMPTY; } if (str.length() <= len) { return str; } return str.substring(ZERO, len); } /** * @Description 字串向右擷取 * @author ShengLiu * @date 2018/7/4 * @param str * @param len * @return java.lang.String */ public static String right(String str, int len) { if (str == null) { return null; } if (len < ZERO) { return EMPTY; } if (str.length() <= len) { return str; } return str.substring(str.length() - len); } /** * @Description 根據不同名字的長度返回不同的顯示資料 * @author ShengLiu * @date 2018/7/4 * @param str * @return java.lang.String */ public static String checkNameLength(String str){ if(str == null){ return null; } if(str.length() == ONE) { return str; }else if(str.length() == TWO){ return "*" + TestUtil.right(str, ONE); }else if(str.length() == THREE){ return TestUtil.left(str, ONE) + "*" + TestUtil.right(str, ONE); }else if(str.length() == FOUR){ return TestUtil.left(str, ONE) + "**" + TestUtil.right(str, ONE); } return str; } /** * 測試 */ public static void main(String[] args) { System.out.println("名字: " + TestUtil.checkNameLength("海")); System.out.println("名字: " + TestUtil.checkNameLength("賊王")); System.out.println("名字: " + TestUtil.checkNameLength("海賊王")); System.out.println("名字: " + TestUtil.checkNameLength("大海賊王")); System.out.println("手機號: " + TestUtil.left("15838883888", THREE) + "*****" + TestUtil.right("15838883888", FOUR)); System.out.println("信用卡號16位: " + TestUtil.left("1234567891011121", FOUR) + "*****" + TestUtil.right("1234567891011121", FOUR)); System.out.println("銀行卡號19位: " + TestUtil.left("1234567891011121314", FOUR) + "*****" + TestUtil.right("1234567891011121314", FOUR)); } }