如何通过提取每个 unichar 来枚举 NSString?我可以使用 characterAtIndex,但这比使用递增的 unichar* 慢。我在 Apple 的文档中没有看到任何不需要将字符串复制到第二个缓冲区的内容。
像这样的东西是理想的:
for (unichar c in string) { ... }
或
unichar* ptr = (unichar*)string;
最佳答案
您可以通过先将 -characterAtIndex:
转换为 IMP 形式来加快速度:
NSString *str = @"This is a test";
NSUInteger len = [str length]; // only calling [str length] once speeds up the process as well
SEL sel = @selector(characterAtIndex:);
// using typeof to save my fingers from typing more
unichar (*charAtIdx)(id, SEL, NSUInteger) = (typeof(charAtIdx)) [str methodForSelector:sel];
for (int i = 0; i < len; i++) {
unichar c = charAtIdx(str, sel, i);
// do something with C
NSLog(@"%C", c);
}
编辑:看来 CFString
Reference包含以下方法:
const UniChar *CFStringGetCharactersPtr(CFStringRef theString);
这意味着您可以执行以下操作:
const unichar *chars = CFStringGetCharactersPtr((__bridge CFStringRef) theString);
while (*chars)
{
// do something with *chars
chars++;
}
如果您不想分配内存来处理缓冲区,这是可行的方法。
关于objective-c - 通过指针枚举 NSString 字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10198913/