-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathContents.swift
68 lines (47 loc) · 1.58 KB
/
Contents.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
//: Playground - noun: a place where people can play
import Foundation
/*:
Brute-Force string search implementation as String extension:
*/
extension String {
func indexOf(_ string: String) -> String.Index? {
for i in self.indices {
var j = i
var found = true
for k in string.indices {
if j == self.endIndex || self[j] != string[k] {
found = false
break
} else {
j = self.index(after: j)
}
}
if found {
return i
}
}
return nil
}
}
//: Usage
let string = "😄😂💩🤦♂️🤖🤯💩"
let pattern = "💩"
let index = string.indexOf(pattern)
print("Found index for \(pattern): " , index as Any)
/*:
Brute-Force string search implementation as String extension (using range(of:) method) which is much faster than the previous implementation:
*/
extension String {
func indicesOf(_ string: String) -> [Int]? {
var indices = [Int]()
var position = self.startIndex
while let range = range(of: string, options: String.CompareOptions.caseInsensitive, range: position ..< self.endIndex, locale: nil) {
indices.append(distance(from: self.startIndex, to: range.lowerBound))
position = index(after: range.lowerBound)
}
return indices
}
}
//: Usage:
let indices = string.indicesOf(pattern)
print("Found index for \(pattern): " , indices as Any)