NSString简单细说(六)—— 字符串的长度

版本记录

版本号 时间
V1.0 2017.05.05

前言

前面我简单的写了些NSString的初始化,写了几篇,都不难,但是可以对新手有一定的小帮助,对于大神级人物可以略过这几篇,NSString本来就没有难的,都是细枝末节,忘记了查一下就会了,没有技术难点,下面我们继续~~~
1. NSString简单细说(一)—— NSString整体架构
2. NSString简单细说(二)—— NSString的初始化
3. NSString简单细说(三)—— NSString初始化
4. NSString简单细说(四)—— 从URL初始化
5. NSString简单细说(五)—— 向文件或者URL写入

详述

求字符串的长度

一、length

先看代码吧。

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

```

然后看输出结果。

```
2017-05-06 18:21:28.747 NSString你会用吗?[6591:221295] length--15
2017-05-06 18:21:28.748 NSString你会用吗?[6591:221295] length--19
2017-05-06 18:21:28.748 NSString你会用吗?[6591:221295] length--14
2017-05-06 18:21:28.748 NSString你会用吗?[6591:221295] length--4
```
**结论**:求长度时我特意加了汉字和空格字符,可以看见他们和英文字符在计算长度时是一样看待的。

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

### 二、- (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);


```
看输出结果。

```
2017-05-06 18:31:20.727 NSString你会用吗?[6726:228362] utf8Legth-6---utf16Length--12
2017-05-06 18:31:20.728 NSString你会用吗?[6726:228362] utf8Legth2-11---utf16Length2--22

```

**结论**:这个求长度空格也算字符,不同的编码格式长度也是不一样的。当存储空间或者存储值大于NSIntegerMax的情况就会返回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);

```

看输出结果。

```
2017-05-06 18:42:28.014 NSString你会用吗?[6863:236467] utf8Legth-18---utf16Length--12
2017-05-06 18:42:28.014 NSString你会用吗?[6863:236467] utf8Legth2-33---utf16Length2--22
```

**结论**:这个一般不怎么用,输出的长度一般也是大于实际的长度。


##  求字符串的字节或者字符

### 一、- (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);

```
看结果。

```
2017-05-06 19:05:21.830 NSString你会用吗?[7115:251324] strLength--31
2017-05-06 19:05:21.831 NSString你会用吗?[7115:251324] chr--3
2017-05-06 19:05:21.913 NSString你会用吗?[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

```
**结论**:这里要注意长度,超过字符串的长度会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你会用吗?[7600:273930] b
2017-05-06 19:37:47.825 NSString你会用吗?[7600:273930] w
2017-05-06 19:37:47.825 NSString你会用吗?[7600:273930] g
2017-05-06 19:37:47.825 NSString你会用吗?[7600:273930] i
2017-05-06 19:37:47.826 NSString你会用吗?[7600:273930] g
2017-05-06 19:37:47.826 NSString你会用吗?[7600:273930] w
2017-05-06 19:37:47.826 NSString你会用吗?[7600:273930] i
2017-05-06 19:37:47.826 NSString你会用吗?[7600:273930] �

```

**结论**:这里注意range的length不能超过字符串的长度,要拷贝的地址buffer的长度也不能小于range的长度,必须确保buffer足够大。

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


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

这个方法的参数有点多,我们先看一下。

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


这里有一个options枚举类型,如下:
```
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]);
    }

```

看输出结果。

```
2017-05-06 22:25:26.491 NSString你会用吗?[8138:301537] isSuccess--1
2017-05-06 22:25:26.492 NSString你会用吗?[8138:301537] A
2017-05-06 22:25:26.492 NSString你会用吗?[8138:301537] �
2017-05-06 22:25:26.493 NSString你会用吗?[8138:301537] �

```
**结论**:这个方法的参数比较长,我工作这么久基本没用过这个方法,今天也是看文档,才看见这个方法,大家看看就可以了。

#  后记

>   今天是周六先写这么多吧,我要休息一下了,哈哈,未完,待续,欢迎留言和批评指正~~~




![美女](http://upload-images.jianshu.io/upload_images/3691932-89ff0227b5959c3c.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/500)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,425评论 4 361
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,058评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,186评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,848评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,249评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,554评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,830评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,536评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,239评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,505评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,004评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,346评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,999评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,060评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,821评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,574评论 2 271
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,480评论 2 267

推荐阅读更多精彩内容