NSRange的定義
1
2
3
4
5
|
typedef struct _NSRange
{
NSUInteger location;
NSUInteger length;
} NSRange;
|
NSRange是一個結構體,其中location是一個以0爲開始的index,length是表示對象的長度。他們都是NSUInteger類型。 而NSUInteger類型的定義如下:
1
2
3
4
5
|
#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
1
2
3
4
5
6
7
8
9
|
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]);
|
搜索字符串:
1
2
3
4
5
6
|
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
下面這個例子將從後向前反向搜索字符串:
1
2
3
4
5
6
7
8
|
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。它提供了完整的正則表達式實現。
如果你要獲取一個字符串或者一個數組中的一個子集,那麼使用NSRange會很方便的定義這個子集。
NSRange定義
1
2
3
4
|
Declaration: typedef struct _NSRange {
NSUInteger location;
NSUInteger length;
} NSRange;
|
創建NSRange的方法定義
1
2
3
4
|
Declaration: NSRange NSMakeRange (
NSUInteger loc,
NSUInteger len
);
|
例如獲取一個數組的一個子集:
1
2
|
NSRange range = NSMakeRange(0, 5);
NSArray *subArray = [self.states subarrayWithRange:range];
|
這樣就獲得了這個數組中0開始的5個元素的子集。