NSString簡(jiǎn)單細(xì)說(shuō)(六)—— 字符串的長(zhǎng)度

版本記錄

版本號(hào) 時(shí)間
V1.0 2017.05.05

前言

前面我簡(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ě)入

詳述

求字符串的長(zhǎng)度

一、length

先看代碼吧造垛。

    NSString *str1 = @"uidgiugeo1e2eyy";
    NSLog(@"length--%ld",str1.length);
    
    NSString *str2 = @"uid  giug  eo1e2eyy";//中間加載一起是4個(gè)空格
    NSLog(@"length--%ld",str2.length);
    
    NSString *str3 = @"uid 我的eo1e2eyy";//中間是一個(gè)空格
    NSLog(@"length--%ld",str3.length);
    
    NSString *str4 = @"我的我的";
    NSLog(@"length--%ld",str4.length);

```

然后看輸出結(jié)果魔招。

```
2017-05-06 18:21:28.747 NSString你會(huì)用嗎?[6591:221295] length--15
2017-05-06 18:21:28.748 NSString你會(huì)用嗎五辽?[6591:221295] length--19
2017-05-06 18:21:28.748 NSString你會(huì)用嗎办斑?[6591:221295] length--14
2017-05-06 18:21:28.748 NSString你會(huì)用嗎?[6591:221295] length--4
```
**結(jié)論**:求長(zhǎng)度時(shí)我特意加了漢字和空格字符杆逗,可以看見(jiàn)他們和英文字符在計(jì)算長(zhǎng)度時(shí)是一樣看待的乡翅。

----------------

### 二吁讨、- (NSUInteger)lengthOfBytesUsingEncoding:(NSStringEncoding)enc;

我們先看代碼。
```
    /**
     *2.- (NSUInteger)lengthOfBytesUsingEncoding:(NSStringEncoding)enc;
     *
     *  @param enc:The encoding for which to determine the receiver's length.
     *
     *  @return :The number of bytes required to store the receiver in the encoding enc in a non-external representation. The length does not include space for a terminating NULL character. Returns 0 if the specified encoding cannot be used to convert the receiver or if the amount of memory required for storing the results of the encoding conversion would exceed NSIntegerMax.
     */

    NSString *str1 = @"AABBCC";
    NSInteger utf8Legth = [str1 lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
    NSInteger utf16Length = [str1 lengthOfBytesUsingEncoding:NSUTF16StringEncoding];
    NSLog(@"utf8Legth-%ld---utf16Length--%ld",utf8Legth,utf16Length);
    
    NSString *str2 = @"A A B B C C";
    NSInteger utf8Legth2 = [str2 lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
    NSInteger utf16Length2 = [str2 lengthOfBytesUsingEncoding:NSUTF16StringEncoding];
    NSLog(@"utf8Legth2-%ld---utf16Length2--%ld",utf8Legth2,utf16Length2);


```
看輸出結(jié)果峦朗。

```
2017-05-06 18:31:20.727 NSString你會(huì)用嗎建丧?[6726:228362] utf8Legth-6---utf16Length--12
2017-05-06 18:31:20.728 NSString你會(huì)用嗎?[6726:228362] utf8Legth2-11---utf16Length2--22

```

**結(jié)論**:這個(gè)求長(zhǎng)度空格也算字符波势,不同的編碼格式長(zhǎng)度也是不一樣的翎朱。當(dāng)存儲(chǔ)空間或者存儲(chǔ)值大于NSIntegerMax的情況就會(huì)返回0。

------------

### 三尺铣、- (NSUInteger)maximumLengthOfBytesUsingEncoding:(NSStringEncoding)enc;

看代碼拴曲。

```
    /**
     *3.- (NSUInteger)maximumLengthOfBytesUsingEncoding:(NSStringEncoding)enc;  
     *
     *  @param enc:The encoding for which to determine the receiver's length.
     *
     *  @return :The maximum number of bytes needed to store the receiver in encoding in a non-external representation. The length does not include space for a terminating NULL character. Returns 0 if the amount of memory required for storing the results of the encoding conversion would exceed NSIntegerMax.
     
     *  @noti:The result is an estimate and is returned in O(1) time; the estimate may be considerably greater than the actual length needed.
     */

        NSString *str1 = @"AABBCC";
        NSInteger utf8Legth = [str1 maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding];
        NSInteger utf16Length = [str1 maximumLengthOfBytesUsingEncoding:NSUTF16StringEncoding];
        NSLog(@"utf8Legth-%ld---utf16Length--%ld",utf8Legth,utf16Length);
    
        NSString *str2 = @"A A B B C C";
        NSInteger utf8Legth2 = [str2 maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding];
        NSInteger utf16Length2 = [str2 maximumLengthOfBytesUsingEncoding:NSUTF16StringEncoding];
        NSLog(@"utf8Legth2-%ld---utf16Length2--%ld",utf8Legth2,utf16Length2);

```

看輸出結(jié)果。

```
2017-05-06 18:42:28.014 NSString你會(huì)用嗎凛忿?[6863:236467] utf8Legth-18---utf16Length--12
2017-05-06 18:42:28.014 NSString你會(huì)用嗎澈灼?[6863:236467] utf8Legth2-33---utf16Length2--22
```

**結(jié)論**:這個(gè)一般不怎么用,輸出的長(zhǎng)度一般也是大于實(shí)際的長(zhǎng)度店溢。


##  求字符串的字節(jié)或者字符

### 一叁熔、- (unichar)characterAtIndex:(NSUInteger)index;

看代碼。

```
    /**
     *1.- (unichar)characterAtIndex:(NSUInteger)index;
     *
     *  @param index:The index of the character to retrieve. 
                     Important:Raises an NSRangeException if index lies beyond the end of the receiver.
     *
     *  @return :The character at the array position given by index.Returns the character at a given UTF-16 code unit index.
     
     *  @noti:You should always use the rangeOfComposedCharacterSequenceAtIndex: or rangeOfComposedCharacterSequencesForRange: method to determine character boundaries, so that any surrogate pairs or character clusters are handled correctly.
     */
    
    NSString *str = @"bwgigwiw753674560FGGEQOWNVHJDYT";
    NSInteger strLength = str.length;
    NSLog(@"strLength--%ld",strLength);
    unichar *chr = [str characterAtIndex:10];
    NSLog(@"chr--%c",chr);
    unichar *chr1 = [str characterAtIndex:32];
    NSLog(@"chr1--%c",chr1);

```
看結(jié)果床牧。

```
2017-05-06 19:05:21.830 NSString你會(huì)用嗎荣回?[7115:251324] strLength--31
2017-05-06 19:05:21.831 NSString你會(huì)用嗎?[7115:251324] chr--3
2017-05-06 19:05:21.913 NSString你會(huì)用嗎戈咳?[7115:251324] *** Terminating app due to uncaught exception 'NSRangeException', reason: '-[__NSCFConstantString characterAtIndex:]: Range or index out of bounds'
*** First throw call stack:
(
    0   CoreFoundation                      0x000000010ff18d4b __exceptionPreprocess + 171
    1   libobjc.A.dylib                     0x000000010f97a21e objc_exception_throw + 48
    2   CoreFoundation                      0x000000010ff822b5 +[NSException raise:format:] + 197

```
**結(jié)論**:這里要注意長(zhǎng)度心软,超過(guò)字符串的長(zhǎng)度會(huì)crash并throw exception。

---------------

### 二著蛙、-  (void)getCharacters:(unichar *)buffer range:(NSRange)range;

看代碼删铃。

```

    /**
     *2.- (void)getCharacters:(unichar *)buffer range:(NSRange)range; 
     *
     *  @desc :Copies characters from a given range in the receiver into a given buffer.
     *
     *  @param buffer:Upon return, contains the characters from the receiver. buffer must be large enough to contain the characters in the range aRange (aRange.length*sizeof(unichar)).    
     *  @param range: The range of characters to retrieve. The range must not exceed the bounds of the receiver.Important:Raises an NSRangeException if any part of aRange lies beyond the bounds of the receiver.
     
     */
    
    NSString *str = @"bwgigwiw753674560FGGEQOWNVHJDYT";
    NSInteger strLength = str.length;
    NSRange range = NSMakeRange(0, 7);
    unichar buffer[10];
    [str getCharacters: buffer range:range];
    for (NSInteger i = 0; i < 10; i++) {
        NSLog(@"%c",buffer[i]);
    }


```

看輸出。

```
2017-05-06 19:37:47.824 NSString你會(huì)用嗎踏堡?[7600:273930] b
2017-05-06 19:37:47.825 NSString你會(huì)用嗎猎唁?[7600:273930] w
2017-05-06 19:37:47.825 NSString你會(huì)用嗎?[7600:273930] g
2017-05-06 19:37:47.825 NSString你會(huì)用嗎暂吉?[7600:273930] i
2017-05-06 19:37:47.826 NSString你會(huì)用嗎胖秒?[7600:273930] g
2017-05-06 19:37:47.826 NSString你會(huì)用嗎?[7600:273930] w
2017-05-06 19:37:47.826 NSString你會(huì)用嗎慕的?[7600:273930] i
2017-05-06 19:37:47.826 NSString你會(huì)用嗎?[7600:273930] ?

```

**結(jié)論**:這里注意range的length不能超過(guò)字符串的長(zhǎng)度挤渔,要拷貝的地址buffer的長(zhǎng)度也不能小于range的長(zhǎng)度肮街,必須確保buffer足夠大。

---------------


### 三判导、- (BOOL)getBytes:(void ***)buffer maxLength:(NSUInteger)maxBufferCount usedLength:(NSUInteger )usedBufferCount encoding:(NSStringEncoding)encoding options:(NSStringEncodingConversionOptions)options range:(NSRange)range remainingRange:(NSRangePointer)leftover;

這個(gè)方法的參數(shù)有點(diǎn)多嫉父,我們先看一下沛硅。

![參數(shù)列表](http://upload-images.jianshu.io/upload_images/3691932-419d4e3cb756d6bc.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/500)


這里有一個(gè)options枚舉類(lèi)型,如下:
```
typedef NS_OPTIONS(NSUInteger, NSStringEncodingConversionOptions) {
    //允許文件丟失
    NSStringEncodingConversionAllowLossy = 1,
    //不允許文件丟失
    NSStringEncodingConversionExternalRepresentation = 2
};
```
接著看代碼绕辖。

```
    /**
     *3.- (BOOL)getBytes:(void *)buffer maxLength:(NSUInteger)maxBufferCount usedLength:(NSUInteger *)usedBufferCount encoding:(NSStringEncoding)encoding options:(NSStringEncodingConversionOptions)options range:(NSRange)range remainingRange:(NSRangePointer)leftover;
     *
     *  @param buffer:A buffer into which to store the bytes from the receiver. The returned bytes are not NULL-terminated.
     *  @param maxBufferCount: The maximum number of bytes to write to buffer.
     *  @param usedBufferCount:The number of bytes used from buffer. Pass NULL if you do not need this value.
     *  @param encoding: The encoding to use for the returned bytes. For possible values, see NSStringEncoding.
     *  @param options: A mask to specify options to use for converting the receiver’s contents to encoding (if conversion is necessary).
     *  @param range:The range of characters in the receiver to get. (aRange.length*sizeof(unichar)).
     *  @param leftover: The remaining range. Pass NULL If you do not need this value.
     
     *  @return : YES if some characters were converted, otherwise NO.
     */

    NSString *str = @"A";
    unichar buffer[10];
    NSUInteger maxBufferCount = 9;
    NSRange range = NSMakeRange(0, 1);

    BOOL isSuccess = [str getBytes:buffer maxLength:maxBufferCount usedLength:NULL encoding:NSUTF8StringEncoding options:NSStringEncodingConversionExternalRepresentation range:range remainingRange:NULL];
    NSLog(@"isSuccess--%d",isSuccess);
    for (NSInteger i = 0; i < 10; i++) {
        NSLog(@"%c",buffer[i]);
    }

```

看輸出結(jié)果摇肌。

```
2017-05-06 22:25:26.491 NSString你會(huì)用嗎?[8138:301537] isSuccess--1
2017-05-06 22:25:26.492 NSString你會(huì)用嗎仪际?[8138:301537] A
2017-05-06 22:25:26.492 NSString你會(huì)用嗎围小?[8138:301537] ?
2017-05-06 22:25:26.493 NSString你會(huì)用嗎?[8138:301537] ?

```
**結(jié)論**:這個(gè)方法的參數(shù)比較長(zhǎng)树碱,我工作這么久基本沒(méi)用過(guò)這個(gè)方法肯适,今天也是看文檔,才看見(jiàn)這個(gè)方法成榜,大家看看就可以了框舔。

#  后記

> ??今天是周六先寫(xiě)這么多吧,我要休息一下了赎婚,哈哈刘绣,未完,待續(xù)挣输,歡迎留言和批評(píng)指正~~~




![美女](http://upload-images.jianshu.io/upload_images/3691932-89ff0227b5959c3c.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/500)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末额港,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子歧焦,更是在濱河造成了極大的恐慌移斩,老刑警劉巖,帶你破解...
    沈念sama閱讀 206,602評(píng)論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件绢馍,死亡現(xiàn)場(chǎng)離奇詭異向瓷,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)舰涌,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,442評(píng)論 2 382
  • 文/潘曉璐 我一進(jìn)店門(mén)猖任,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人瓷耙,你說(shuō)我怎么就攤上這事朱躺。” “怎么了搁痛?”我有些...
    開(kāi)封第一講書(shū)人閱讀 152,878評(píng)論 0 344
  • 文/不壞的土叔 我叫張陵长搀,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我鸡典,道長(zhǎng)源请,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 55,306評(píng)論 1 279
  • 正文 為了忘掉前任,我火速辦了婚禮谁尸,結(jié)果婚禮上舅踪,老公的妹妹穿的比我還像新娘。我一直安慰自己良蛮,他們只是感情好抽碌,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,330評(píng)論 5 373
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著决瞳,像睡著了一般货徙。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上瞒斩,一...
    開(kāi)封第一講書(shū)人閱讀 49,071評(píng)論 1 285
  • 那天破婆,我揣著相機(jī)與錄音,去河邊找鬼胸囱。 笑死祷舀,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的烹笔。 我是一名探鬼主播裳扯,決...
    沈念sama閱讀 38,382評(píng)論 3 400
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼谤职!你這毒婦竟也來(lái)了饰豺?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 37,006評(píng)論 0 259
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤允蜈,失蹤者是張志新(化名)和其女友劉穎冤吨,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體饶套,經(jīng)...
    沈念sama閱讀 43,512評(píng)論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡漩蟆,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 35,965評(píng)論 2 325
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了妓蛮。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片怠李。...
    茶點(diǎn)故事閱讀 38,094評(píng)論 1 333
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖蛤克,靈堂內(nèi)的尸體忽然破棺而出捺癞,到底是詐尸還是另有隱情,我是刑警寧澤构挤,帶...
    沈念sama閱讀 33,732評(píng)論 4 323
  • 正文 年R本政府宣布髓介,位于F島的核電站,受9級(jí)特大地震影響儿倒,放射性物質(zhì)發(fā)生泄漏版保。R本人自食惡果不足惜呜笑,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,283評(píng)論 3 307
  • 文/蒙蒙 一夫否、第九天 我趴在偏房一處隱蔽的房頂上張望彻犁。 院中可真熱鬧,春花似錦凰慈、人聲如沸汞幢。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 30,286評(píng)論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)森篷。三九已至,卻和暖如春豺型,著一層夾襖步出監(jiān)牢的瞬間仲智,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 31,512評(píng)論 1 262
  • 我被黑心中介騙來(lái)泰國(guó)打工姻氨, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留钓辆,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 45,536評(píng)論 2 354
  • 正文 我出身青樓肴焊,卻偏偏與公主長(zhǎng)得像前联,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子娶眷,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,828評(píng)論 2 345

推薦閱讀更多精彩內(nèi)容