-1

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.

LakaLe_
  • 454
  • 1
  • 6
  • 15

3 Answers3

2

There is several ways to do so, you can do it with :

  • Range ;
  • Regular Expression ;
  • ...

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).

lchamp
  • 6,592
  • 2
  • 19
  • 27
1

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!

Stefan Arentz
  • 34,311
  • 8
  • 67
  • 88
-1

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.

riodoro1
  • 1,246
  • 7
  • 14
  • 1
    There is no need to clip the string. Just pass a new range to `rangeOfString:options:range:`. – rmaddy Feb 27 '15 at 15:22
  • This is a very bad answer. There are a number of options in `NSString` to find occurrences of substrings or regular expression matches. – Stefan Arentz Feb 28 '15 at 02:58