NSRange 用法

摘自:http://hi.baidu.com/ferrari_yang/blog/item/811e92c299396e0a0ef477a7.html

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

// 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: {253}。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: {122}

ac

如果你要獲取一個字符串或者一個數組中的一個子集,那麼使用NSRange會很方便的定義這個子集。

NSRange定義

Declaration: typedef struct _NSRange {

   NSUInteger location;

   NSUInteger length;

} NSRange;

創建NSRange的方法定義

Declaration: NSRange NSMakeRange (

     NSUInteger loc,

     NSUInteger len

  );

例如獲取一個數組的一個子集:

        NSRange range = NSMakeRange(05); 

        NSArray *subArray = [self.states subarrayWithRange:range];

這樣就獲得了這個數組中0開始的5個元素的子集。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章