的抽象NSString
是UTF-16“字符”。如果你想要 UTF-32,那么从 Cocoa 的角度来看,它不再是一个字符串;它是一个数据缓冲区。所以,你要找的是:
NSData* utf32Data = [someString dataUsingEncoding:NSUTF32StringEncoding];
uint32_t* utf32 = (uint32_t*)[utf32Data bytes];
NSUInteger count = [utf32Data length] / sizeof(utf32[0]);
然后遍历数组的count
元素。utf32
NSString
这是用于转换范围的未经测试的类别:
@interface NSString (UTF32Range)
- (NSRange) rangeFromUTF32Range:(NSRange)range;
@end
@implementation NSString (UTF32Range)
- (NSRange) rangeFromUTF32Range:(NSRange)range
{
NSUInteger len = self.length;
NSUInteger i = 0;
while (i < range.location && i < len)
{
unichar u = [self characterAtIndex:i];
if (CFStringIsSurrogateHighCharacter(u))
{
range.location++;
i++;
}
i++;
}
while (i < range.length && i < len)
{
unichar u = [self characterAtIndex:i];
if (CFStringIsSurrogateHighCharacter(u))
{
range.length++;
i++;
}
i++;
}
return range;
}
@end