基本上,我想制作一个程序,如果您开始输入姓名,该应用程序将从数据库中识别它并为您填写姓名。要做到这一点,如果一个人在完成一个名字后键入一个逗号,该应用程序将开始记录下一个名字是什么。如果它匹配为数据库中其中一个名称的子字符串,它将为用户填写。问题是我需要获取在 textField 字符串中最后一次出现逗号字符之后到目前为止填写的名称的哪一部分,但我不知道如何。例如: 用户类型:“Daniel, Joh” 该应用程序会为您填写 John。谢谢。
最佳答案
如果你真的想要最后一个逗号之后的字符,你可以使用正则表达式:
let string = "Hamilton, A"
let regex = try! NSRegularExpression(pattern: ",\\s*(\\S[^,]*)$")
if let match = regex.firstMatch(in: string, range: string.nsRange), let result = string[match.range(at: 1)] {
// use `result` here
}
哪里,在 Swift 4 中:
extension String {
/// An `NSRange` that represents the full range of the string.
var nsRange: NSRange {
return NSRange(startIndex ..< endIndex, in: self)
}
/// Substring from `NSRange`
///
/// - Parameter nsRange: `NSRange` within the string.
/// - Returns: `Substring` with the given `NSRange`, or `nil` if the range can't be converted.
subscript(nsRange: NSRange) -> Substring? {
return Range(nsRange, in: self)
.flatMap { self[$0] }
}
}
关于string - 如何在字符串 : Swift IOS 中最后一次出现字符后获取子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36905301/