java hide 方法_java之使用*号做脱敏的两种实现方式

/**

* 替换指定字符串的指定区间内字符为"*"

*

* @param str 字符串

* @param startInclude 开始位置(包含)

* @param endExclude 结束位置(不包含)

* @return 替换后的字符串

* @since 4.1.14

*/

public static String hide(CharSequence str, int startInclude, int endExclude) {

return replace(str, startInclude, endExclude, '*');

}

接着replace方法实现如下:

/**

* 替换指定字符串的指定区间内字符为固定字符

*

* @param str 字符串

* @param startInclude 开始位置(包含)

* @param endExclude 结束位置(不包含)

* @param replacedChar 被替换的字符

* @return 替换后的字符串

* @since 3.2.1

*/

public static String replace(CharSequence str, int startInclude, int endExclude, char replacedChar) {

if (isEmpty(str)) {

return str(str);

}

final int strLength = str.length();

if (startInclude > strLength) {

return str(str);

}

if (endExclude > strLength) {

endExclude = strLength;

}

if (startInclude > endExclude) {

// 如果起始位置大于结束位置,不替换

return str(str);

}

// 初始化一个长度为11的字符数组

final char[] chars = new char[strLength];

for (int i = 0; i < strLength; i++) {

if (i >= startInclude && i < endExclude) {

chars[i] = replacedChar;

} else {

chars[i] = str.charAt(i);

}

}

return new String(chars);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值