Swift4.0字符串相关处理

Swift4.0字符串相关处理

字符串截取

  • 截取某字符串的前10个字符串:

    1
    let sub1 = str.prefix(10)
  • 截取某字符串的后10个字符串:

    1
    let str1 = str.suffix(10)
  • 截取某字符串的后10个字符串,也可以换种写法:

    1
    2
    let index2 = str.index(str.endIndex, offsetBy: -10)
    let sub4 = str[index2..<str.endIndex]
  • 截取某字符串的第3个字符到第6个字符范围的字符串
    1
    2
    3
    let index3 = str.index(str.startIndex, offsetBy: 3)
    let index4 = str.index(str.startIndex, offsetBy: 6)
    let sub4 = str[index3..<index4]

字符串替换

  • 将手机号中间四位数隐藏
    1
    2
    3
    4
    let phone = "13576836715"
    let startIndex = phone.index(phone.startIndex, offsetBy:3)
    let endIndex = phone.index(startIndex, offsetBy:4)
    let result = phone.replacingCharacters(in: startIndex..<endIndex, with:"****")

结果是result = "135****6715"

Swift4.0 UITextfield限制输入位数

1
2
3
4
5
6
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let maxLength = 3
let currentString: NSString = textField.text! as NSString
let newString: NSString = currentString.replacingCharacters(in: range, with: string) as NSString
return newString.length <= maxLength
}