2016-09-06 57 views
3

我的Swift應用程序涉及在UITextView中搜索文本。用戶可以在該文本視圖中搜索特定的子字符串,然後在文本視圖中跳轉到該字符串的任何實例(比如第三個實例)。我需要找出它們所在的字符的整數值。在Swift中查找字符串中第N個子字符串實例的索引

例如:

實施例1:用戶搜索「你好」和文本視圖讀取「哎喜你好,嘿喜你好」,則用戶按下向下箭頭,以查看第二個實例。我需要知道第二個hello中的第一個h的整數值(即,hello中h的哪個#字符在文本視圖內)。整數值應該是22

實施例2:爲「ABC」,而文本視圖讀取「ABCD」和他們正在尋找的abc第一個實例,因此整數值應1(這是該整數值的用戶搜索a,因爲它是他們正在搜索的實例的第一個字符)。

如何獲取用戶正在搜索的字符的索引?

+1

這主要是重複的http://stackoverflow.com/questions/28685420/search-string-for-repeating-instances-of-a-word – rmaddy

+0

@rmaddy似乎對我有幫助,但不完全正是我在這裏問。謝謝你。 – owlswipe

+2

答案正是你一般需要的。通過傳遞從第一個子字符串結尾開始的範圍來獲得第二個子字符串。 – rmaddy

回答

6

嘗試這樣的:

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個β6•夫特3

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

看起來不錯,讓我試試...(謝謝!) – owlswipe

+0

啊,完全有效! – owlswipe

+0

非常感謝。 – owlswipe

2

另一種方法是NSRegularExpression其被設計成很容易地通過在一個字符串匹配迭代。如果您使用.ignoreMetacharacters選項,它將不會應用任何複雜的通配符/正則表達式邏輯,但只會查找有問題的字符串。所以考慮:

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]) 

你可以使用enumerateMatches

var count = 0 
let range = NSRange(string.startIndex ..< string.endIndex, in: string) 
regex.enumerateMatches(in: string, range: range) { result, _, stop in 
    count += 1 
    if count == matchToFind { 
     print(result!.range.location) 
     stop.pointee = true 
    } 
} 

或者,你可以找到所有的人都用matches(in:range:),然後抓住第n之一:

let matches = regex.matches(in: string, range: range) 
if matches.count >= matchToFind { 
    print(matches[matchToFind - 1].range.location) 
} 

顯然,如果您非常喜歡,則可以省略.ignoreMetacharacters選項並允許用戶執行正則表達式搜索(例如通配符,全文搜索,詞的開始等)。

對於Swift 2,請參閱previous revision of this answer

+0

哦,看上,謝謝你的回答。 – owlswipe

相關問題