在Swift中查找string中的子串的第N个实例的索引

我的Swift应用程序涉及在UITextView中search文本。 用户可以在该文本视图中search特定的子string,然后在文本视图中跳转到该string的任何实例(比如第三个实例)。 我需要找出他们在哪个字符的整数值。

例如:

示例1:用户search“hello”,文本视图显示“hello you hello,hello you hello”,然后用户按下箭头查看second实例。 我需要知道第二个hello中的第一个h的整数值(即,hello中的h个字符在文本视图中)。 整数值应该是22

例2:用户search“abc”,而文本视图为“abcd”,他们正在寻找abc的第一个实例,所以整数值应该是1 (这是a的整数值,因为它是第一个字符他们正在search的实例)。

我怎样才能得到用户正在寻找的字符的索引?

尝试像这样:

 let sentence = "hey hi hello, hey hi hello" let query = "hello" var searchRange = sentence.startIndex..<sentence.endIndex var indexes: [String.Index] = [] while let range = sentence.rangeOfString(query, options: .CaseInsensitiveSearch, range: searchRange) { searchRange = range.endIndex..<searchRange.endIndex indexes.append(range.startIndex) } print(indexes) // "[7, 21]\n" 

Xcode 8 beta 6•Swift 3

 while let range = sentence.range(of: query, options: .caseInsensitive, range: searchRange) { searchRange = range.upperBound..<searchRange.upperBound indexes.append(range.lowerBound) } 

另一种方法是NSRegularExpression ,它被devise成可以很容易地遍历string中的匹配。 如果使用.IgnoreMetacharacters选项,它将不会应用任何复杂的通配符/正则expression式逻辑,但只会查找有问题的string。 所以考虑:

 let string = "hey hi hello, hey hi hello" // string to search within let searchString = "hello" // string to search for let matchToFind = 2 // grab the second occurrence let regex = try! NSRegularExpression(pattern: searchString, options: [.CaseInsensitive, .IgnoreMetacharacters]) 

你可以使用enumerateMatchesInString

 var count = 0 regex.enumerateMatchesInString(string, options: [], range: NSRange(location: 0, length: string.characters.count)) { result, _, stop in count += 1 if count == matchToFind { print(result!.range.location) stop.memory = true } } 

或者你可以用matchesInStringfind它们,然后抓住第n个:

 let matches = regex.matchesInString(string, options: [], range: NSRange(location: 0, length: string.characters.count)) if matches.count >= matchToFind { print(matches[matchToFind - 1].range.location) } 

显然,如果你这么倾向,你可以省略.IgnoreMetacharacters选项,并允许用户执行正则expression式search(例如通配符,全文search,单词开始等)。