版本記錄
版本號(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)