2017-04-05 11 views

回答

2

只需使用range(of:)即可。示例:

let haystack = Data(bytes: [1, 2, 3, 4, 5, 6]) 
let needle = Data(bytes: [3, 4]) 

if let range = haystack.range(of: needle) { 
    print("Found at", range.lowerBound, "..<", range.upperBound) 
    // Found at 2 ..< 4 
} 

您可以选择指定搜索范围和/或向后搜索。例如:

let haystack = Data(bytes: [1, 2, 1, 2, 1, 2, 1, 2, 1, 2]) 
let needle = Data(bytes: [1, 2]) 

if let range = haystack.range(of: needle, options: .backwards, in: 2..<7) { 
    print("Found at", range.lowerBound, "..<", range.upperBound) 
    // Found at 4 ..< 6 
} 
相关问题