通过指针枚举NSString字符 [英] Enumerate NSString characters via pointer
问题描述
如何通过拉出每个unichar来枚举NSString?我可以使用characterAtIndex,但是比做一个递增unichar *慢。我没有看到任何在苹果的文档,不需要将字符串复制到第二个缓冲区。
How can I enumerate NSString by pulling each unichar out of it? I can use characterAtIndex but that is slower than doing it by an incrementing unichar*. I didn't see anything in Apple's documentation that didn't require copying the string into a second buffer.
这样的东西是理想的:
for (unichar c in string) { ... }
或
unichar* ptr = (unichar*)string;
推荐答案
您可以加快 characterAtIndex:
,首先将其转换为IMP格式:
You can speed up -characterAtIndex:
by converting it to it's IMP form first:
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);
}
EDIT:看起来 CFString
/ a>包含以下方法:
It appears that the CFString
Reference contains the following method:
const UniChar *CFStringGetCharactersPtr(CFStringRef theString);
这意味着您可以执行以下操作:
This means you can do the following:
const unichar *chars = CFStringGetCharactersPtr((__bridge CFStringRef) theString);
while (*chars)
{
// do something with *chars
chars++;
}
如果你不想分配内存来处理缓冲区,要走的路。
If you don't want to allocate memory for coping the buffer, this is the way to go.
这篇关于通过指针枚举NSString字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!