I need NSRange objects for the position of each uppercase letter in a given NSString for input into a method for a custom attributed string class.
There are of course quite a few ways to accomplish this such as rangeOfString:options: with NSRegularExpressionSearch or using RegexKitLite to get each match separately while walking the string.
What would be the fastest performing approach to accomplish this task?
The simplest way is probably to use
-rangeOfCharacterFromSet:options:range:with[NSCharacterSet uppercaseLetterCharacterSet]. By modifying the range to search over with each call, you can find all of the uppercase letters pretty easily. Something like the following will work to give you an NSArray of all ranges (encoded as NSValues):Note, this will not coalesce adjacent ranges into a single range, but that’s easy enough to add.
Here’s an alternative solution based on NSScanner:
Unlike the last, this one does coalesce adjacent uppercase characters into a single range.
Edit: If you’re looking for absolute speed, this one will likely be the fastest of the 3 presented here, while still preserving correct unicode support (note, I have not tried compiling this):