NSRange and NSString Objects
When poking around NSString methods you’ll find many references to NSRange, which is nothing more than a C structure that is helpful for describing a series of items, including a starting location and a count. For example, a range is helpful to extract a substring from another string, where you specify the starting location and number of elements needed (examples to follow).
NSRange Definition
NSRange is a structure defined as follows:
typedef struct _NSRange { NSUInteger location; NSUInteger length; } NSRange;
location is the starting index in the range (zero based) and length is the number of entries in the range. NSUInteger is simply an unsigned value that supports both 32 and 64 bit systems. Here is how NSUInteger is defined:
#if __LP64__ || TARGET_OS_EMBEDDED || TARGET_OS_IPHONE || TARGET_OS_WIN32 || NS_BUILD_32_LIKE_64 typedef unsigned long NSUInteger; #else typedef unsigned int NSUInteger; #endif
NSRange and Strings
The example below shows one approach for creating a range and using the same to extract a substring – the output from below is IPA
NSString *homebrew = @"Imperial India Pale Ale (IPA)"; // Starting at position 25, get 3 characters NSRange range = NSMakeRange (25, 3); // This would also work: // NSRange range = {25, 3}; NSLog (@"Beer shortname: %@", [homebrew substringWithRange:range]);
If you want to search for a substring, you could write something like the following:
NSString *homebrew = @"Imperial India Pale Ale (IPA)"; NSRange range = [homebrew rangeOfString:@"IPA"]; // Did we find the string "IPA" ? if (range.length > 0) NSLog(@"Range is: %@", NSStringFromRange(range));
The output from above will display: Range is: {25, 3}. Notice the call to NSStringFromRange() which will display the return value (a range) as an NSString. There is also a function to create a range from a string: NSRangeFromString().
Let’s look at one more example, the code below will search for the string “ia” starting at the end of the string moving towards the beginning:
NSString *homebrew = @"Imperial India Pale Ale (IPA)"; // Search for the "ia" starting at the end of string NSRange range = [homebrew rangeOfString:@"ia" options:NSBackwardsSearch]; // What did we find if (range.length > 0) NSLog(@"Range is: %@", NSStringFromRange(range));
The result from above is: Range is: {12, 2} (the “ia” inside the word “India”).
NSRange Functions
Here is a list of functions that work with ranges:
NSEqualRanges()
NSIntersectionRange()
NSLocationInRange()
NSMakeRange()
NSMaxRange()
NSRangeFromString()
NSStringFromRange()
NSUnionRange()
Related posts:
- Compare NSString Objects (Updated)
- Using NSScanner to convert Hex to RGB Color
- How to Get Width/Size/Length of UIString in a Specific Font



RegexKitLite lets you do even more awesome things with NSString and NSRange:
http://regexkit.sourceforge.net/RegexKitLite/index.html
[Reply]
Thanks John, very helpful
[Reply]