版本記錄
| 版本號(hào) | 時(shí)間 |
|---|---|
| V1.0 | 2017.05.07 |
前言
前面我簡(jiǎn)單的寫(xiě)了些NSString的初始化,寫(xiě)了幾篇,都不難,但是可以對(duì)新手有一定的小幫助,對(duì)于大神級(jí)人物可以略過(guò)這幾篇,NSString本來(lái)就沒(méi)有難的,都是細(xì)枝末節(jié),忘記了查一下就會(huì)了,沒(méi)有技術(shù)難點(diǎn),下面我們繼續(xù)~~~
1. NSString簡(jiǎn)單細(xì)說(shuō)(一)—— NSString整體架構(gòu)
2. NSString簡(jiǎn)單細(xì)說(shuō)(二)—— NSString的初始化
3. NSString簡(jiǎn)單細(xì)說(shuō)(三)—— NSString初始化
4. NSString簡(jiǎn)單細(xì)說(shuō)(四)—— 從URL初始化
5. NSString簡(jiǎn)單細(xì)說(shuō)(五)—— 向文件或者URL寫(xiě)入
6. NSString簡(jiǎn)單細(xì)說(shuō)(六)—— 字符串的長(zhǎng)度
7. NSString簡(jiǎn)單細(xì)說(shuō)(七)—— 與C字符串的轉(zhuǎn)化
詳述
識(shí)別和比較字符串
一、- (NSComparisonResult)caseInsensitiveCompare:(NSString *)string;
這個(gè)用于字符串的比較,比較結(jié)果是個(gè)枚舉NSComparisonResult。如下:
typedef enum NSComparisonResult : NSInteger {
NSOrderedAscending = -1L,
NSOrderedSame,
NSOrderedDescending
} NSComparisonResult;
```
這里
```
NSOrderedAscending //左邊的小于右邊的
The left operand is smaller than the right operand.
NSOrderedSame //左邊的字符串等于右邊的
The two operands are equal.
NSOrderedDescending //左邊的字符串大于右邊的
The left operand is greater than the right operand.
```
下面我們直接看代碼。
```
/**
*1.- (NSComparisonResult)caseInsensitiveCompare:(NSString *)string;
*
* @param string:The string with which to compare the receiver.
*
* @return :Returns an NSComparisonResult value that indicates the lexical ordering. NSOrderedAscending the receiver precedes aString in lexical ordering, NSOrderedSame the receiver and aString are equivalent in lexical value, and NSOrderedDescending if the receiver follows aString.
*
*/
NSString *ocStr1 = @"AABBCC";
NSString *ocStr2 = @"aABBCC";
NSString *ocStr3 = @"AABCCC";
NSComparisonResult result1 = [ocStr1 caseInsensitiveCompare:ocStr2];
NSLog(@"result1--%ld",result1);
NSComparisonResult result2 = [ocStr1 caseInsensitiveCompare:ocStr3];
NSLog(@"result2--%ld",result2);
```
看結(jié)果。
```
2017-05-07 15:06:52.485 NSString你會(huì)用嗎?[2596:103484] result1--0
2017-05-07 15:06:52.485 NSString你會(huì)用嗎?[2596:103484] result2---1
```
**結(jié)論**:0代表左右相等,也就是說(shuō)這個(gè)方法比較不區(qū)分大小寫(xiě),-1代表上升,左邊小于右邊,1代表下降,左邊大于右邊。因?yàn)閛cStr1的第四位是B,ocStr3的第四位是C,則前者小于后者,返回的是-1。需要說(shuō)明的是這個(gè)方法和 compare:options:方法option 參數(shù)取值NSCaseInsensitiveSearch時(shí)是一樣的。當(dāng)處理的字符串是要呈現(xiàn)給用戶時(shí),需要使用的是localizedCaseInsensitiveCompare:方法。為什么要用這個(gè)方法?因?yàn)橛行┱Z(yǔ)言并不是基于英文字母的。例如: 對(duì)于漢語(yǔ)字符,就存在[A-Z]字母表和漢字發(fā)音之間的對(duì)應(yīng)關(guān)系, 而且對(duì)于app用戶而言, 漢語(yǔ)字符順序'基本上'是基于發(fā)音的。'基本上'意味著并不是100%遵從這條規(guī)則。有些生僻漢字不是基于發(fā)音 (這些漢字如此生僻, 以至于你可以認(rèn)為發(fā)音就是正確的排序規(guī)則)。
----------
### 二、- (NSComparisonResult)localizedCaseInsensitiveCompare:(NSString *)string;
看代碼。
```
/**
*2. - (NSComparisonResult)localizedCaseInsensitiveCompare:(NSString *)string;
*
* @param string:This value must not be nil. If this value is nil, the behavior is undefined and may change in future versions of macOS.
*
* @return :Returns an NSComparisonResult value that indicates the lexical ordering. NSOrderedAscending the receiver precedes aString in lexical ordering, NSOrderedSame the receiver and aString are equivalent in lexical value, and NSOrderedDescending if the receiver follows aString.
*
*/
NSString *ocStr1 = @"good morning";
NSString *ocStr2 = @"早上好";
NSComparisonResult result1 = [ocStr1 localizedCaseInsensitiveCompare:ocStr2];
NSLog(@"result1--%ld",result1);
```
看結(jié)果。
```
2017-05-07 15:50:06.849 NSString你會(huì)用嗎?[3211:138318] result1---1
```
**結(jié)論**:這個(gè)要根據(jù)locale來(lái)確定,是不區(qū)分大小寫(xiě)的比較。
-----------
### 三、- (NSComparisonResult)compare:(NSString *)string;
看代碼。
```
/**
*3. - (NSComparisonResult)compare:(NSString *)string;
*
* @param string:This value must not be nil. If this value is nil, the behavior is undefined and may change in future versions of macOS.
*
* @return :Returns an NSComparisonResult value that indicates the lexical ordering. NSOrderedAscending the receiver precedes aString in lexical ordering, NSOrderedSame the receiver and aString are equivalent in lexical value, and NSOrderedDescending if the receiver follows aString.
*
*/
NSString *ocStr1 = @"AABBCC";
NSString *ocStr2 = @"aABBCC";
NSString *ocStr3 = @"AABCCC";
NSComparisonResult result1 = [ocStr1 compare:ocStr2];
NSLog(@"result1--%ld",result1);
NSComparisonResult result2 = [ocStr1 compare:ocStr3];
NSLog(@"result2--%ld",result2);
```
看結(jié)果。
```
2017-05-07 16:02:02.135 NSString你會(huì)用嗎?[3373:145514] result1---1
2017-05-07 16:02:02.136 NSString你會(huì)用嗎?[3373:145514] result2---1
```
**結(jié)論**:結(jié)果是-1,都是上升的,左邊小于右邊,也就是說(shuō)它們的比較是區(qū)分大小寫(xiě)的。同樣,如果處理的文本是要呈現(xiàn)給用戶時(shí),這時(shí)候使用的應(yīng)該是localizedStandardCompare: 方法。
-------------
### 四、- (NSComparisonResult)localizedCompare:(NSString *)string;
```
/**
*4. - (NSComparisonResult)localizedCompare:(NSString *)string;
*
* @param string:This value must not be nil. If this value is nil, the behavior is undefined and may change in future versions of macOS.
*
* @return :Returns an NSComparisonResult value that indicates the lexical ordering. NSOrderedAscending the receiver precedes aString in lexical ordering, NSOrderedSame the receiver and aString are equivalent in lexical value, and NSOrderedDescending if the receiver follows aString.
*
*/
NSString *ocStr1 = @"早上好";
NSString *ocStr2 = @"早上好";
NSComparisonResult result1 = [ocStr1 localizedCompare:ocStr2];
NSLog(@"result1--%ld",result1);
```
看結(jié)果。
```
2017-05-07 16:15:13.405 NSString你會(huì)用嗎?[3750:157885] result1--0
```
**結(jié)論**:本地化字符串的比較,同樣,如果處理的文本是要呈現(xiàn)給用戶時(shí),這時(shí)候使用的應(yīng)該是localizedStandardCompare: 方法。
----------
### 五、- (NSComparisonResult)compare:(NSString *)string options:(NSStringCompareOptions)mask;
這里重要的就是這個(gè)option參數(shù),如下:
```
typedef NS_OPTIONS(NSUInteger, NSStringCompareOptions) {
//不區(qū)分大小寫(xiě)的比較
NSCaseInsensitiveSearch = 1,
//區(qū)分大小寫(xiě)的比較
NSLiteralSearch = 2, /* Exact character-by-character equivalence */
//從字符串末尾開(kāi)始搜索
NSBackwardsSearch = 4, /* Search from end of source string */
//搜索限制范圍的字符串
NSAnchoredSearch = 8, /* Search is limited to start (or end, if NSBackwardsSearch) of source string */
//按照字符串里面的數(shù)字為依據(jù)進(jìn)行比較
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 */
//忽略"-"符號(hào)的比較
NSDiacriticInsensitiveSearch NS_ENUM_AVAILABLE(10_5, 2_0) = 128, /* If specified, ignores diacritics (o-umlaut == o) */
//忽略字符串的長(zhǎng)度算出比較結(jié)果
NSWidthInsensitiveSearch NS_ENUM_AVAILABLE(10_5, 2_0) = 256, /* If specified, ignores width differences ('a' == UFF41) */
//忽略不區(qū)分大小寫(xiě)比較的選項(xiàng),并強(qiáng)制返回NSOrderedAscending 或者 NSOrderedDescending
NSForcedOrderingSearch NS_ENUM_AVAILABLE(10_5, 2_0) = 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) */
////只能應(yīng)用于 rangeOfString:..., stringByReplacingOccurrencesOfString:...和 replaceOccurrencesOfString:... 方法。使用通用兼容的比較方法,如果設(shè)置此項(xiàng),可以去掉 NSCaseInsensitiveSearch 和 NSAnchoredSearch
NSRegularExpressionSearch NS_ENUM_AVAILABLE(10_7, 3_2) = 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 */
};
```
下面看代碼。
```
/**
*5. - (NSComparisonResult)compare:(NSString *)string options:(NSStringCompareOptions)mask;
*
* @param string:This value must not be nil. If this value is nil, the behavior is undefined and may change in future versions of macOS.
* @param mask:Options for the search—you can combine any of the following using a C bitwise OR operator: NSCaseInsensitiveSearch, NSLiteralSearch, NSNumericSearch. See String Programming Guide for details on these options.
*
* @return :Returns an NSComparisonResult value that indicates the lexical ordering. NSOrderedAscending the receiver precedes aString in lexical ordering, NSOrderedSame the receiver and aString are equivalent in lexical value, and NSOrderedDescending if the receiver follows aString.
*
*/
//不區(qū)分大小寫(xiě)
NSString *ocStr1 = @"AABBCC";
NSString *ocStr2 = @"aABBCC";
NSComparisonResult result1 = [ocStr1 compare:ocStr2 options:NSCaseInsensitiveSearch];
NSLog(@"result1--%ld",result1);
//嚴(yán)格區(qū)分大小寫(xiě)
NSString *ocStr3 = @"AABBCC";
NSString *ocStr4 = @"aABBCC";
NSComparisonResult result2 = [ocStr3 compare:ocStr4 options:NSLiteralSearch];
NSLog(@"result2--%ld",result2);
//倒序比較
NSString *ocStr5 = @"AABBCC";
NSString *ocStr6 = @"aABBCA";
NSComparisonResult result3 = [ocStr5 compare:ocStr6 options:NSBackwardsSearch];
NSLog(@"result3--%ld",result3);
//數(shù)字比較
NSString *ocStr7 = @"AAB33BCC";
NSString *ocStr8 = @"aAB44BCC";
NSComparisonResult result4 = [ocStr7 compare:ocStr8 options:NSNumericSearch];
NSLog(@"result4--%ld",result4);
```
下面看結(jié)果。
```
2017-05-07 16:50:09.606 NSString你會(huì)用嗎?[4229:183365] result1--0
2017-05-07 16:50:09.606 NSString你會(huì)用嗎?[4229:183365] result2---1
2017-05-07 16:50:09.606 NSString你會(huì)用嗎?[4229:183365] result3---1
2017-05-07 16:50:09.607 NSString你會(huì)用嗎?[4229:183365] result4---1
```
**結(jié)論**:如果處理的文本是要呈現(xiàn)給用戶時(shí),這時(shí)候使用的應(yīng)該是localizedStandardCompare: 方法,或者使用compare:options:range:locale:,傳入用戶的locale。還有這里的mask參數(shù),不一定是一個(gè)單一的枚舉值,還可以是很多個(gè)枚舉值一起使用,利用或"|"進(jìn)行連接使用。
-----------
### 六、- (NSComparisonResult)compare:(NSString *)string options:(NSStringCompareOptions)mask range:(NSRange)rangeOfReceiverToCompare;
??這個(gè)大家應(yīng)該很清楚,和五中的方法相比,差的就是range這一個(gè)參數(shù),也就是說(shuō)這個(gè)方法可以比較一定區(qū)間的大小,當(dāng)range的范圍是整個(gè)字符串的時(shí)候,就可以看做和五方法是等價(jià)的了。下面看代碼。
```
/**
*6. - (NSComparisonResult)compare:(NSString *)string options:(NSStringCompareOptions)mask range:(NSRange)rangeOfReceiverToCompare;
*
* @param string:This value must not be nil. If this value is nil, the behavior is undefined and may change in future versions of macOS.
* @param mask:Options for the search—you can combine any of the following using a C bitwise OR operator: NSCaseInsensitiveSearch, NSLiteralSearch, NSNumericSearch. See String Programming Guide for details on these options.
* @param range:the range of string for comparision.
*
* @return :Returns an NSComparisonResult value that indicates the lexical ordering. NSOrderedAscending the receiver precedes aString in lexical ordering, NSOrderedSame the receiver and aString are equivalent in lexical value, and NSOrderedDescending if the receiver follows aString.
*
*/
//不區(qū)分大小寫(xiě)
NSString *ocStr1 = @"AABBCC";
NSString *ocStr2 = @"AABBCA";
NSRange range1 = NSMakeRange(0, ocStr1.length);
NSComparisonResult result1 = [ocStr1 compare:ocStr2 options:NSCaseInsensitiveSearch range:range1];
NSLog(@"result1==%ld",result1);
NSRange range2 = NSMakeRange(0, 1);
NSComparisonResult result2 = [ocStr1 compare:ocStr2 options:NSCaseInsensitiveSearch range:range2];
NSLog(@"result2==%ld",result2);
```
看結(jié)果。
```
2017-05-07 17:18:28.943 NSString你會(huì)用嗎?[4669:202369] result1==1
2017-05-07 17:18:28.944 NSString你會(huì)用嗎?[4669:202369] result2==-1
```
**結(jié)論**:如果處理的文本是要呈現(xiàn)給用戶時(shí),這時(shí)候使用的應(yīng)該是localizedStandardCompare: 方法,或者使用compare:options:range:locale:,傳入用戶的locale。range也不能越界,否則會(huì)報(bào)錯(cuò),NSRangeException。
--------------
### 七、- (NSComparisonResult)compare:(NSString *)string options:(NSStringCompareOptions)mask range:(NSRange)rangeOfReceiverToCompare locale:(id)locale;
看代碼。
```
/**
*7. - (NSComparisonResult)compare:(NSString *)string options:(NSStringCompareOptions)mask range:(NSRange)rangeOfReceiverToCompare locale:(id)locale;
*
* @param string:This value must not be nil. If this value is nil, the behavior is undefined and may change in future versions of macOS.
* @param mask:Options for the search—you can combine any of the following using a C bitwise OR operator: NSCaseInsensitiveSearch, NSLiteralSearch, NSNumericSearch. See String Programming Guide for details on these options.
* @param range:the range of string for comparision.
* @param locale:An instance of NSLocale. To use the current locale, pass [NSLocale currentLocale]. For example, if you are comparing strings to present to the end-user, use the current locale. To use the system locale, pass nil.
*
* @return :Returns an NSComparisonResult value that indicates the lexical ordering. NSOrderedAscending the receiver precedes aString in lexical ordering, NSOrderedSame the receiver and aString are equivalent in lexical value, and NSOrderedDescending if the receiver follows aString.
*
*/
NSString *ocStr1 = @"AABBCC";
NSString *ocStr2 = @"AABBCA";
NSRange range1 = NSMakeRange(0, ocStr1.length);
NSComparisonResult result1 = [ocStr1 compare:ocStr2 options:NSCaseInsensitiveSearch range:range1 locale:[NSLocale currentLocale]];
NSLog(@"result1==%ld",result1);
```
看結(jié)果。
```
2017-05-07 17:26:37.468 NSString你會(huì)用嗎?[4790:209130] result1==1
```
**結(jié)論**:如果處理的文本是要呈現(xiàn)給用戶時(shí),這時(shí)候使用的應(yīng)該是localizedStandardCompare: 方法,或者使用compare:options:range:locale:,傳入用戶的locale。range也不能越界,否則會(huì)報(bào)錯(cuò),NSRangeException。還有就是locale
這個(gè)參數(shù),使用當(dāng)?shù)?,就傳[NSLocale currentLocale],使用系統(tǒng)的就用nil。需要注意的是locale參數(shù)影響的是相等和排序算法,例如在一些地區(qū),重音字符要排在普通字符之后,在另外一寫(xiě)地區(qū)將他們排在"z"之后。
-------------
### 八、- (NSComparisonResult)localizedStandardCompare:(NSString *)string;
```
/**
*8. - (NSComparisonResult)localizedStandardCompare:(NSString *)string;
*
* @param string:This value must not be nil. If this value is nil, the behavior is undefined and may change in future versions of macOS.
*
* @return :Returns an NSComparisonResult value that indicates the lexical ordering. NSOrderedAscending the receiver precedes aString in lexical ordering, NSOrderedSame the receiver and aString are equivalent in lexical value, and NSOrderedDescending if the receiver follows aString.
*
*/
NSString *ocStr1 = @"AABBCC";
NSString *ocStr2 = @"AABBCA";
NSComparisonResult result1 = [ocStr1 localizedStandardCompare:ocStr2];
NSLog(@"result1==%ld",result1);
```
看結(jié)果。
```
2017-05-07 17:35:37.829 NSString你會(huì)用嗎?[4929:214923] result1==1
```
**結(jié)論**:利用這個(gè)方法進(jìn)行排序,在不同的地區(qū)排序結(jié)果是不一樣的,并且在未來(lái)發(fā)布版本的時(shí)候還可能會(huì)發(fā)生變化,這個(gè)方法的locale使用的是current locale。
-------------
### 九、- (BOOL)hasPrefix:(NSString *)str;
看代碼。
```
/**
*9. - (BOOL)hasPrefix:(NSString *)str;
*
* @param string:a string
*
* @return :YES if aString matches the beginning characters of the receiver, otherwise NO. Returns NO if aString is empty.
*
*/
NSString *ocStr1 = @"AABBCC";
BOOL isHasPrefix = [ocStr1 hasPrefix:@"AA"];
NSLog(@"isHasPrefix==%d",isHasPrefix);
BOOL isHasPrefix1 = [ocStr1 hasPrefix:@"AAA"];
NSLog(@"isHasPrefix1==%d",isHasPrefix1);
```
看結(jié)果。
```
2017-05-07 17:45:08.300 NSString你會(huì)用嗎?[5087:224155] isHasPrefix==1
2017-05-07 17:45:08.301 NSString你會(huì)用嗎?[5087:224155] isHasPrefix1==0
```
**結(jié)論**:這里就不解釋了,0就是表示不以所選擇的字符串做前綴,1就表示以所選擇的字符串做前綴。需要說(shuō)的是,這個(gè)方法可以看做方法五中的option為 NSAnchoredSearch的特殊情況。
-------------
### 十、- (BOOL)hasSuffix:(NSString *)str;
看代碼。
```
/**
*10. - (BOOL)hasSuffix:(NSString *)str;
*
* @param string:a string
*
* @return :YES if aString matches the beginning characters of the receiver, otherwise NO. Returns NO if aString is empty.
*
*/
NSString *ocStr1 = @"AABBCC";
BOOL isHasPrefix = [ocStr1 hasSuffix:@"BCC"];
NSLog(@"isHasPrefix==%d",isHasPrefix);
BOOL isHasPrefix1 = [ocStr1 hasSuffix:@"ABCC"];
NSLog(@"isHasPrefix1==%d",isHasPrefix1);
```
看結(jié)果。
```
2017-05-07 17:50:28.910 NSString你會(huì)用嗎?[5206:228422] isHasPrefix==1
2017-05-07 17:50:28.911 NSString你會(huì)用嗎?[5206:228422] isHasPrefix1==0
```
**結(jié)論**:這里就不解釋了,0就是表示不以所選擇的字符串做后綴,1就表示以所選擇的字符串做后綴。需要說(shuō)的是,這個(gè)方法可以看做方法五中的option為 NSAnchoredSearch的特殊情況。
--------------
### 十一、- (BOOL)isEqualToString:(NSString *)aString;
先看代碼。
```
/**
*11. - (BOOL)isEqualToString:(NSString *)aString;
*
* @param aString:The string with which to compare the receiver.
*
* @return :YES if aString is equivalent to the receiver (if they have the same id or if they are NSOrderedSame in a literal comparison), otherwise NO.
*
*/
NSString *ocStr1 = @"AABBCC";
NSString *ocStr2 = @"AABBCD";
BOOL isEqualStr = [ocStr1 isEqualToString:ocStr2];
NSLog(@"isEqualStr==%d",isEqualStr);
```
看結(jié)果。
```
2017-05-07 18:09:41.126 NSString你會(huì)用嗎?[5444:242832] isEqualStr==0
```
**結(jié)論**:這個(gè)比較是采用標(biāo)準(zhǔn)的字符串進(jìn)行比較的,也就是說(shuō)用字符串的長(zhǎng)度乘以UTF-16單位編碼長(zhǎng)度組成該字符串。當(dāng)比較時(shí),如果單個(gè)編碼相同時(shí),字符串就是相同的,比較時(shí)比較的是UTF-16編碼單元。比如“?” 表示由“O” (U+004F LATIN CAPITAL LETTER O) 和 “¨” (U+0308 COMBINING DIAERESIS) 組成,不會(huì)與“?” 這個(gè)代表單個(gè)編碼字符 (U+00D6 LATIN CAPITAL LETTER O WITH DIAERESIS)進(jìn)行比較。而且如果你確定兩個(gè)比較的對(duì)象是字符串時(shí),該方法要優(yōu)于方法isEqual:。
-------------
### 十二、@property(readonly) NSUInteger hash;
一個(gè)無(wú)符號(hào)的整形數(shù)字作為哈希表的地址,看代碼。
```
/**
*12. @property(readonly) NSUInteger hash;
*
*/
NSString *ocStr1 = @"AABBCC";
NSString *ocStr2 = @"AABBCC";
NSUInteger ocStr1Hash = ocStr1.hash;
NSUInteger ocStr2Hash = ocStr2.hash;
NSLog(@"ocStr1Hash==%lu,ocStr2Hash==%lu",ocStr1Hash,ocStr2Hash);
if (ocStr1Hash == ocStr2Hash) {
NSLog(@"他倆是相等的字符串");
}
```
看結(jié)果。
```
2017-05-07 18:22:51.766 NSString你會(huì)用嗎?[5640:252521] ocStr1Hash==6494203873124370,ocStr2Hash==6494203873124370
2017-05-07 18:22:51.766 NSString你會(huì)用嗎?[5640:252521] 他倆是相等的字符串
```
**結(jié)論**:相等的字符串擁有相同的hash值。
# 后記
> ??兩天的假期就這么結(jié)束了,這個(gè)今天就寫(xiě)這么多了,NSString剩下的以后寫(xiě),未完,待續(xù)~~~
