在Swift中查找字符串中第N个子字符串实例的索引 [英] Find index of Nth instance of substring in string in Swift

查看:330
本文介绍了在Swift中查找字符串中第N个子字符串实例的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Swift应用程序涉及在UITextView中搜索文本.用户可以在该文本视图中搜索某个子字符串,然后跳转到该文本视图中该字符串的任何实例(例如,第三个实例).我需要找出它们所在的字符的整数值.

My Swift app involves searching through text in a UITextView. The user can search for a certain substring within that text view, then jump to any instance of that string in the text view (say, the third instance). I need to find out the integer value of which character they are on.

例如:

示例1:用户搜索"hello",并且文本视图显示为你好,你好",然后用户按下箭头查看第二个实例.我需要知道第二个hello中第一个h的整数值(即,h中的#个字符在文本视图中).整数值应为22.

Example 1: The user searches for "hello" and the text view reads "hey hi hello, hey hi hello", then the user presses down arrow to view second instance. I need to know the integer value of the first h in the second hello (i.e. which # character that h in hello is within the text view). The integer value should be 22.

示例2:当文本视图读取"abcd"时,用户搜索"abc",并且他们正在寻找abc的第一个实例,因此整数值应为1 (这是该a的整数值,因为它是他们正在搜索的实例的第一个字符).

Example 2: The user searches for "abc" while the text view reads "abcd" and they are looking for the first instance of abc, so the integer value should be 1 (which is the integer value of that a since it's the first character of the instance they're searching for).

如何获取用户正在搜索的字符的索引?

How can I get the index of the character the user is searching for?

推荐答案

Xcode 11•Swift 5或更高版本

let sentence = "hey hi hello, hey hi hello"
let query = "hello"
var searchRange = sentence.startIndex..<sentence.endIndex
var indices: [String.Index] = []

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

print(indices)   // "[7, 21]\n"

这篇关于在Swift中查找字符串中第N个子字符串实例的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆