網頁

2012年5月19日 星期六

(ios) NSString (五)【compare:】

【環境:xCode4.2 , ios5.1】
宣告:-(NSComparisonResult)compare:(NSString *)string1 option:(NSStringCompareOptions)mask range:(NSRange)range
名稱:用compare對字串中的字元進行逐一比較
說明:NSComparisonResult傳回的類型(註一),option為一個遮罩參數(註二),range表示要比較的範圍(註三

<以下範例>
 
    NSString *string1 = @"this blog is n11 studio";
    NSString *string2 = @"n11 studio";
    NSRange myRange;
    myRange.location = 13;
    myRange.length = 10;
    NSComparisonResult result = [string1 compare:string2 options:NSCaseInsensitiveSearch range:myRange];
    if(result == NSOrderedSame)
    {
        NSLog(@"it is the same");
    } 

註一:回傳的類型有三種,官方文件如下。如果出現第一個字元不相同時,若string1的該位置字元比string2的該字元於字母表中更前面時,則回傳NSOrderedAscending。如"a compare:b"
enum _NSComparisonResult {NSOrderedAscending = -1, NSOrderedSame, NSOrderedDescending};
typedef NSInteger NSComparisonResult;

#if NS_BLOCKS_AVAILABLE
typedef NSComparisonResult (^NSComparator)(id obj1, id obj2);
#endif

註二:以下為官方文件,內容說明很多種搜尋方法,NSCaseInsensitiveSearch:比較時不區分大小寫
/* These options apply to the various search/find and comparison methods (except where noted).
*/
enum {
    NSCaseInsensitiveSearch = 1,
    NSLiteralSearch = 2,  /* Exact character-by-character equivalence */
    NSBackwardsSearch = 4,  /* Search from end of source string */
    NSAnchoredSearch = 8,  /* Search is limited to start (or end, if NSBackwardsSearch) of source string */
    NSNumericSearch = 64  /* Added in 10.2; Numbers within strings are compared using numeric value, that is, Foo2.txt < Foo7.txt < Foo25.txt; only applies to compare methods, not find */
#if MAC_OS_X_VERSION_10_5 <= MAC_OS_X_VERSION_MAX_ALLOWED || __IPHONE_2_0 <= __IPHONE_OS_VERSION_MAX_ALLOWED
    ,
    NSDiacriticInsensitiveSearch = 128, /* If specified, ignores diacritics (o-umlaut == o) */
    NSWidthInsensitiveSearch = 256, /* If specified, ignores width differences ('a' == UFF41) */
    NSForcedOrderingSearch = 512 /* If specified, comparisons are forced to return either NSOrderedAscending or NSOrderedDescending if the strings are equivalent but not strictly equal, for stability when sorting (e.g. "aaa" > "AAA" with NSCaseInsensitiveSearch specified) */
#endif /* MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5 */
#if MAC_OS_X_VERSION_10_7 <= MAC_OS_X_VERSION_MAX_ALLOWED || __IPHONE_3_2 <= __IPHONE_OS_VERSION_MAX_ALLOWED
    ,
    NSRegularExpressionSearch = 1024    /* Applies to rangeOfString:..., stringByReplacingOccurrencesOfString:..., and replaceOccurrencesOfString:... methods only; the search string is treated as an ICU-compatible regular expression; if set, no other options can apply except NSCaseInsensitiveSearch and NSAnchoredSearch */
#endif /* MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7 || __IPHONE_3_2 <= __IPHONE_OS_VERSION_MAX_ALLOWED */
};
typedef NSUInteger NSStringCompareOptions;

註三: 用於表示要比較的範圍,記住不能超過接收訊息物件的界限
typedef struct _NSRange {
    NSUInteger location;
    NSUInteger length;
} NSRange;

沒有留言:

張貼留言