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}
ac
如果你要獲取一個字符串或者一個數組中的一個子集,那么使用NSRange會很方便的定義這個子集。
NSRange定義
Declaration: typedef struct _NSRange {
NSUInteger location;
NSUInteger length;
} NSRange;
創建NSRange的方法定義
Declaration: NSRange NSMakeRange (
NSUInteger loc,
NSUInteger len
);
例如獲取一個數組的一個子集:
NSRange range = NSMakeRange(0, 5);
NSArray *subArray = [self.states subarrayWithRange:range];
這樣就獲得了這個數組中0開始的5個元素的子集。
@import url(http://m.shnenglu.com/CuteSoft_Client/CuteEditor/Load.ashx?type=style&file=SyntaxHighlighter.css);@import url(/css/cuteeditor.css);