Skip to content

Instantly share code, notes, and snippets.

@nazmulkp
Last active October 9, 2019 15:56
Show Gist options
  • Save nazmulkp/c3b8e3f5d60cc0bd3b2316e9430d127c to your computer and use it in GitHub Desktop.
Save nazmulkp/c3b8e3f5d60cc0bd3b2316e9430d127c to your computer and use it in GitHub Desktop.
Search Algorithm. .
I looking for in my string exact number of word/sentence for example:<br>
What i am tried:
let str = "Art of swift, now art of swift5 but this is true art of swift from 2014 now what do you think about art of swift?"
var search = "art of swift"
str.contains(word:search)
var count = str.lowercased().components(separatedBy: search.lowercased()).count
print(count - 1)
output:
4
I am looking for it should be `3` because of `art of swift5` not looking for search.
In the example above, it returns 4 because of found "art of swift" in the word "art of swift5". I want a method that will return 3 in that condition.
**But method have more few case:**<br>
**Allow**<br>
case-insensitive for user can be upper case or lower it doesn't matter for search result counter. example user put `Art of swift` in the text string has `art of swift`
Art of swift // it will return true as found 1
any special character allow for example `? , . etc`
art of swift? // it will return true as found 1
even special character with character allow for example `
art of swift's // it will return true as found 1
**Don't allow:**<br>
don't allowing different language character for example
art of swiftবাং // it will return false as not found 0
even it not allowing same language character <br>
art of swiftly // it will return false as not found 0
Why need it?
i am trying to implement search result items show it base on best match priority.
=================================================================================================================
import Foundation
extension String {
func nazmulCount(of needle: String) -> Int {
let pattern = "\\b" + NSRegularExpression.escapedPattern(for: needle) + "\\b"
let rex = try! NSRegularExpression(pattern: pattern, options: [.caseInsensitive])
return rex.matches(in: self, options: [], range: NSRange(startIndex..., in: self)).count
}
}
"Art of swift, now art of swift5 but this is true art of swift from 2014 now what do you think about art of swift?".nazmulCount(of: "art of swift")
// 3
"Art of swift".nazmulCount(of: "art of swift")
// 1
"art of swift?".nazmulCount(of: "art of swift")
// 1
"art of swift's".nazmulCount(of: "art of swift")
// 1
"art of swiftবাং".nazmulCount(of: "art of swift")
// 0
"art of swiftly".nazmulCount(of: "art of swift")
// 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment