2 changed files with 39 additions and 1 deletions
@ -0,0 +1,37 @@ |
|||
package com.project.ding.utils; |
|||
|
|||
/** |
|||
* 中文名字脱敏工具类 |
|||
* 规则: |
|||
* 1. 二字名:第二个字替换为*(如:李*) |
|||
* 2. 三字名:中间字替换为*(如:李*华) |
|||
* 3. 四字名:中间两个字替换为*(如:李**明) |
|||
* 4. 其他长度:保留首尾,中间全部替换为*(如:李***强、*明) |
|||
*/ |
|||
public class ChineseNameEncryptUtil { |
|||
|
|||
/** |
|||
* 脱敏中文名字(优化版) |
|||
* @param chineseName 原始中文名字 |
|||
* @return 脱敏后的名字,空值返回空字符串 |
|||
*/ |
|||
public static String encryptChineseName(String chineseName) { |
|||
// 空值处理
|
|||
if (chineseName == null || chineseName.isBlank()) { |
|||
return ""; |
|||
} |
|||
|
|||
// 去除首尾空格
|
|||
String name = chineseName.trim(); |
|||
int nameLength = name.length(); |
|||
|
|||
// 增强型 switch 表达式(JDK 14+ 支持,可简化为单行返回)
|
|||
return switch (nameLength) { |
|||
case 1 -> name; // 单字名直接返回
|
|||
case 2 -> name.charAt(0) + "*"; // 二字名:首字符 + *
|
|||
case 3 -> name.charAt(0) + "*" + name.charAt(2); // 三字名:首 + * + 尾
|
|||
case 4 -> name.charAt(0) + "**" + name.charAt(3); // 四字名:首 + ** + 尾
|
|||
default -> name.charAt(0) + "*".repeat(nameLength - 2) + name.charAt(nameLength - 1); |
|||
}; |
|||
} |
|||
} |
|||
Loading…
Reference in new issue