Reputation: 10590
I looking for in my string exact number of word/sentence for example:
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:
Allow
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:
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
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.
Upvotes: 1
Views: 527
Reputation: 385700
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
Upvotes: 2