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

版本记录

版本号时间
V1.02017.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)



作者:刀客传奇
链接:https://www.jianshu.com/p/cb27bd76a2d3
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值