To take a single character, you need to know how the string is encoded so that you can position each character in memory. However, the string encoding of iOS is not fixed, so you need to set a uniform encoding format that converts all other formatted strings into a uniform format, and then you can take a single character based on the encoding rules. Here, use the UTF-8 encoding. UTF-8 encoding is widely used, and most of the data transmitted between client and server is UTF-8 encoded.
A detailed description of the UTF-8 can be wiki: UTF-8.
is the UTF-8 encoded format:
The process of development is probably:
- Converts the NSString string to a char string in the UTF-8 format.
- Reads the bytes from the char string from the beginning.
- According to the ' Byte 1 ' field in, judge the current character to occupy a few bytes, and get these several bytes.
- Converts several bytes obtained into a NSString string object.
- Gets the next character, making 3, only to get the last character.
* * One thing to note:
?
| 12345 |
nsstring *string = [NSString stringwithformat:@ "1a Sheets" Code class= "CPP Plain"); const char *chars = [string cstringusingencoding:nsutf8stringencoding]; for ( int i = 0; i < strlen (chars); i++) { &NBSP;&NBSP;&NBSP;&NBSP; printf ( } |
Output: 3161ffffffe5ffffffbcffffffa0
In iOS, ffffff are added to the front of non-ASCII characters, instead of using the starting values specified in the UTF-8 directly.
Here is the code implementation (using categories):
Nsstring+stringtowords.h
?
| 1234567 |
#import <Foundation/Foundation.h>@interface NSString (StringToWords) - (NSArray *)words;@end |
Nsstring+stringtowords.h
?
| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647 |
#import "NSString+StringToWords.h"@implementation NSString (StringToWords)- (NSArray *)words{#if ! __has_feature(objc_arc) NSMutableArray *words = [[[NSMutableArray alloc] init] autorelease];#else NSMutableArray *words = [[NSMutableArray alloc] init];#endif const char *str = [self cStringUsingEncoding:NSUTF8StringEncoding]; char *word; for (int i = 0; i < strlen(str);) { int len = 0; if (str[i] >= 0xFFFFFFFC) { len = 6; } else if (str[i] >= 0xFFFFFFF8) { len = 5; } else if (str[i] >= 0xFFFFFFF0) { len = 4; } else if (str[i] >= 0xFFFFFFE0) { len = 3; } else if (str[i] >= 0xFFFFFFC0) { len = 2; } else if (str[i] >= 0x00) { len = 1; } word = malloc(sizeof(char) * (len + 1)); for (int j = 0; j < len; j++) { word[j] = str[j + i]; } word[len] = ‘\0‘; i = i + len; NSString *oneWord = [NSString stringWithCString:word encoding:NSUTF8StringEncoding]; free(word); [words addObject:oneWord]; } return words;}@end |
http://my.oschina.net/yongbin45/blog/149549
IOS gets a single character in a string