|
|
@@ -158,3 +158,32 @@ extension String {
|
|
|
return .init(width: width!, height: height!)
|
|
|
}
|
|
|
}
|
|
|
+
|
|
|
+extension String {
|
|
|
+ /// 字符串脱敏:展示前后字符,中间用 * 隐藏
|
|
|
+ /// - Parameters:
|
|
|
+ /// - prefixCount: 开头保留的字符数量(默认 1)
|
|
|
+ /// - suffixCount: 结尾保留的字符数量(默认 1)
|
|
|
+ /// - maskSymbol: 隐藏符号(默认 *)
|
|
|
+ /// - Returns: 脱敏后的字符串
|
|
|
+ func hideMiddle(prefixCount: Int = 1, suffixCount: Int = 1, maskSymbol: String = "*") -> String {
|
|
|
+ // 空字符串直接返回
|
|
|
+ guard !isEmpty else { return self }
|
|
|
+
|
|
|
+ let totalCount = count
|
|
|
+ // 总长度 ≤ 前后保留长度之和,直接返回原字符串
|
|
|
+ guard totalCount > prefixCount + suffixCount else { return self }
|
|
|
+
|
|
|
+ // 截取开头
|
|
|
+ let prefix = prefix(prefixCount)
|
|
|
+ // 截取结尾
|
|
|
+ let suffix = suffix(suffixCount)
|
|
|
+ // 计算需要隐藏的字符数量
|
|
|
+ let maskLength = totalCount - prefixCount - suffixCount
|
|
|
+ // 生成对应数量的隐藏符号
|
|
|
+ let mask = String(repeating: maskSymbol, count: maskLength)
|
|
|
+
|
|
|
+ // 拼接结果
|
|
|
+ return prefix + mask + suffix
|
|
|
+ }
|
|
|
+}
|