將15012345678 → 150****5678,指定區間字符替換為*。
/**
* 字符串指定區間替換
* @param source 源字符串
* @param startInclusive 起始索引(含)
* @param endExclusive 結束索引(不含)
* @param replacement 替換字符
* @return 處理後字符串,參數非法返回空串
*/
public static String replaceRange(String source, int startInclusive, int endExclusive, String replacement) {
if (source == null || startInclusive < 0 || endExclusive > source.length() || startInclusive >= endExclusive) {
return "";
}
StringBuilder sb = new StringBuilder(source.length());
sb.append(source, 0, startInclusive); // 前綴
for (int i = startInclusive; i < endExclusive; i++) {
sb.append(replacement); // 替換段
}
sb.append(source, endExclusive, source.length()); // 後綴
return sb.toString();
}
// 使用示例
String phone = "15012345678";
String masked = replaceRange(phone, 3, 7, "*"); // 150****5678
public static String maskPhone(String phone) {
if (phone == null || phone.length() != 11) return phone;
return replaceRange(phone, 3, 7, "****");
}
// 支持多種格式
public static String maskChinesePhone(String phone) {
if (phone == null) return null;
// 去除非數字
String digits = phone.replaceAll("\\D", "");
if (digits.length() == 11) return maskPhone(digits);
return phone; // 非標準長度不處理
}
// 替換第4-7位(索引3-6)
String masked = phone.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
// 或指定位置
String masked = phone.substring(0,3) + "****" + phone.substring(7);
| 方法 | 時間複雜度 | 對象創建 | 推薦場景 |
|---|---|---|---|
| StringBuilder | O(n) | 1個 | 高頻調用、長字符串 |
| substring拼接 | O(n) | 3個 | 簡單固定格式 |
| 正則replaceAll | O(n) | 多個(Pattern編譯) | 一次性/配置化 |