如何转换字符串utf-8?

时间:2013-06-16 16:23:21

标签: ios utf-8 nsstring

我有一个像这样的NSString:

NSString *word = @"119,111,114,100"

所以,我想要做的是将这个NSString转换为单词

所以问题是,我可以通过哪种方式将字符串转换为单词?

3 个答案:

答案 0 :(得分:1)

// I have added some values to your sample input :-)
NSString *word = @"119,111,114,100,32,240,159,145,141";

// Separate components into array:
NSArray *array = [word componentsSeparatedByString:@","];

// Create NSData containing the bytes:
NSMutableData *data = [[NSMutableData alloc] initWithLength:[array count]];
uint8_t *bytes = [data mutableBytes];
for (NSUInteger i = 0; i < [array count]; i++) {
    bytes[i] = [array[i] intValue];
}

// Convert to NSString (interpreting the bytes as UTF-8):
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

NSLog(@"%@", str);

输出:

word 

答案 1 :(得分:0)

试试这个:

NSString *word = @"119,111,114,100";
NSArray *array=[word componentsSeparatedByString:@","];
for (NSString *string in array) {
   char character=[string integerValue];
    NSLog(@"%c",character);    
}

输出:

w
o
r
d

答案 2 :(得分:0)

libicu它是一个UTF8库,它支持从here所述的字节数组转换。

问题是,它提供Java,C或C ++ API,而不是obj-c。