Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/huanglinxiao/article/details/91528192
Given a string and a needle haystack string, a position of the needle to find the first occurrence of the string (starting from 0) in the haystack string. If not, it returns -1.
Example 1:
Input: haystack = "hello", needle = "ll"
Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba"
Output: -1
solution:
func strStr(_ haystack: String, _ needle: String) -> Int {
guard !needle.isEmpty else {
return 0
}
guard needle.count <= haystack.count else {
return -1
}
//1.拿到匹配的字符串needle
//2.在特定的字符串haystack中遍历查找
if haystack.contains(needle) {
let hays: NSString = haystack as NSString
let index:Int = hays.range(of: needle).location
return index
}else{
return -1
}
}