I wonder if there is a "iOS API way" to find in custom NSString string range of every occurrence of word, e.x.
var text: NSString = "John is tall. John is 23."
When I use:
text.rangeOfString("John")
it will return only first one.
I wonder if there is a "iOS API way" to find in custom NSString string range of every occurrence of word, e.x.
var text: NSString = "John is tall. John is 23."
When I use:
text.rangeOfString("John")
it will return only first one.
There is several ways to do so, you can do it with :
For example, with regular expression :
var str = "John is tall. John is 23."
var length = countElements(str)
var regex : NSRegularExpression = NSRegularExpression(pattern: "John", options: NSRegularExpressionOptions.CaseInsensitive, error: nil)!
var nbMatch : Int = regex.numberOfMatchesInString(str, options: NSMatchingOptions.allZeros, range: NSMakeRange(0, length))
println(nbMatch)
Note that you can specify option, here it's case insensitive for example (so "John" or "john" will return the same).
Here is a simple extension on NSString that lets you find occurrences of a substring in a more easy, more Swifty, way:
extension NSString {
func findAllOccurrencesOfString(string: NSString, options: NSStringCompareOptions, _ callback: (NSRange) -> Void) {
var searchRange = NSMakeRange(0, self.length)
while true {
let range = self.rangeOfString(string, options: options, range: searchRange)
if range.location == NSNotFound {
break
}
callback(range)
searchRange = NSMakeRange(range.location + range.length, self.length - (range.location + range.length))
}
}
}
Which you can use as:
let s: NSString = "John is tall. John is 23. Where is John"
s.findAllOccurrencesOfString("John", options: NSStringCompareOptions.allZeros) { (range) -> Void in
println("Found \(s.substringWithRange(range)) at \(range)")
}
This results in:
Found John at (0,4)
Found John at (14,4)
Found John at (35,4)
Enjoy!
I think there is nothing in NSString to do this. Try a loop clipping the string each time "John" is found and adding the range to NSMutableArray.