Swift 用星号替换字符

Swift 用星号替换字符,swift,string,replace,nsstring,Swift,String,Replace,Nsstring,我在操场上有这个密码 我已经将userID和email扩展分开了。但是,我想用*更改电子邮件第一个和最后一个字符之间的字符,除了 我正试图使它与任何电子邮件地址输入足够的动态。有什么想法吗?谢谢你的意见 let email = "asdfg.hjkl@gmail.com" let atSign = email.index(of: "@") ?? email.endIndex let userID = email[..<atSign] print(userID + email.suffix(

我在操场上有这个密码

我已经将userID和email扩展分开了。但是,我想用
*
更改电子邮件第一个和最后一个字符之间的字符,除了

我正试图使它与任何电子邮件地址输入足够的动态。有什么想法吗?谢谢你的意见

let email = "asdfg.hjkl@gmail.com"
let atSign = email.index(of: "@") ?? email.endIndex
let userID = email[..<atSign]
print(userID + email.suffix(from: atSign))
让email=“asdfg。hjkl@gmail.com"
让atSign=email.index(of:“@”)??email.endIndex

让userID=email[…我只找到了一个迭代解决方案:

let email = "asdfg.hjkl@gmail.com"
let atSign = email.index(of: "@") ?? email.endIndex
let userID = email[..<atSign]
print(userID + email.suffix(from: atSign))


var lastLetterInx = email.index(before:atSign)

var inx = email.startIndex

var result = ""
while(true) {
    if (inx >= lastLetterInx) {
        result.append(String(email[lastLetterInx...]))
        break;
    }

    if (inx > email.startIndex && email[inx] != ".") {
        result.append("*")      
    } else {
        result.append(email[inx])
    }

    inx = email.index(after:inx)
}

print (result)
让email=“asdfg。hjkl@gmail.com"
让atSign=email.index(共:“@”)??email.endIndex
让userID=email[..=lastLetterInx){
result.append(字符串(电子邮件[lastLetterInx…]))
打破
}
如果(inx>email.startIndex&&email[inx]!=”){
结果。追加(“*”)
}否则{
结果。追加(电子邮件[inx])
}
inx=email.index(后面是:inx)
}
打印(结果)

这是一个使用正则表达式的解决方案,它只是额外的一行

let email = "asdfg.hjkl@gmail.com"
let atSign = email.index(of: "@") ?? email.endIndex
let userID = email[..<atSign]
let hiddenUserID = userID.replacingOccurrences(of: "(?<!^)[^.]", with: "*", options: .regularExpression)
print(hiddenUserID + email.suffix(from: atSign)) // a****.****@gmail.com
让email=“asdfg。hjkl@gmail.com"
让atSign=email.index(共:“@”)??email.endIndex

让userID=email[…var newString=userID.replacingOccurrences(of:“.”,with:“*”)为什么不像其他人那样做:
let obclustedemail=email[email.startIndex..感谢您的建议,但是对于这个案例,我希望有一个********l@gmail.com而不是asd************com,因为这将稍后在不同的应用程序上使用