NSRange 和 NSString

Posted by Elton's Blog on December 25, 2009

NSRange的定义

typedef struct _NSRange
{
  NSUInteger location;
  NSUInteger length;
} NSRange;

NSRange是一个结构体,其中location是一个以0为开始的index,length是表示对象的长度。他们都是NSUInteger类型。 而NSUInteger类型的定义如下:

#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

例子: 下面这个例子,将输出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]);

搜索字符串:

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

上面的程序将输出Range is: {25, 3}。NSStringFromRange()方法,将一个NSRange返回一个NSString。而另外一个函数NSRangeFromString()则是将NSString转换为NSRange

下面这个例子将从后向前反向搜索字符串:

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

上面的程序将输出:Range is: {12, 2}

Objective-C中没有正则表达式,如果你想使用更复杂的字符串匹配,可以使用这个类库RegexKitLite。它提供了完整的正则表达式实现。