swift 手机号码/邮箱隐藏****

规则:
手机号: 根据位数隐藏四位

(example: 五位:****5;七位:1****67;九位:12****78; 十一位:123****8910 )

邮箱: @符号前只展示第一位和最后一位

(example:1*****[email protected])

    func hidePhoneNumber(number: String) -> String {
        
        if number.count < 5 {
            var str = ""
            for _ in 0 ..< number.count {
                str += "*"
            }
            return str
        } else {
            //替换一段内容,两个参数:替换的范围和用来替换的内容
            let start = number.index(number.startIndex, offsetBy: (number.count - 5) / 2)
            let end = number.index(number.startIndex, offsetBy: (number.count - 5) / 2 + 4)
            let range = Range(uncheckedBounds: (lower: start, upper: end))
            return number.replacingCharacters(in: range, with: "****")
        }
    }
    
    func hideEmail(email: String) -> String {
        var mail = email
        let arraySubstrings: [Substring] = mail.split(separator: "@")
        let arrayStrings: [String] = arraySubstrings.compactMap { "\($0)" } // i将Substring转为string
        var str = ""
        if arrayStrings[0].count < 3 {
            for _ in 0 ..< arrayStrings[0].count {
                str += "*"
            }
            return str + arrayStrings[1]
        } else {
        for _ in 0 ..< arrayStrings[0].count - 2 {
            str += "*"
        }
            let start = mail.index(mail.startIndex, offsetBy: 1)
            let end = mail.index(mail.startIndex, offsetBy: arrayStrings[0].count - 1)
            let range = Range(uncheckedBounds: (lower: start, upper: end))
            mail.replaceSubrange(range, with: str)
            return mail
        }
        
    }
使用:
self.hidePhoneNumber(number: phone)
self.hideEmail(email: email)

注意:
代码不是很完美,位数太少的时候会出错,实际项目中需要有位数限制

你可能感兴趣的:(swift 手机号码/邮箱隐藏****)