Objective C NSString problem

流过昼夜 提交于 2019-12-06 11:56:19

问题


I have a NSString that I need to examine character by character and:

 examine char
    perform calculation
 loop (until string ends)

Any thoughts on the best way to do this? Do I need to convert the NSString to a NSArray or C string?


回答1:


The simplest way to go about it is using NSString's characterAtIndex: method:

int charIndex;
for (charIndex = 0; charIndex < [myString length]; charIndex++)
{
    unichar testChar = [myString characterAtIndex:charIndex];
    //... your code here
}



回答2:


-characterAtIndex: is the simplest approach, but the best is to drop down to CFString and use a CFStringInlineBuffer, as in this method:

- (NSIndexSet *) indicesOfCharactersInSet: (NSCharacterSet *) charset
{
    if ( self.length == 0 )
    return ( nil );

    NSMutableIndexSet * set = [NSMutableIndexSet indexSet];

    CFIndex i = 0;
    UniChar character = 0;
    CFStringInlineBuffer buf;
    CFStringInitInlineBuffer( (CFStringRef)self, &buf, CFRangeMake(0, self.length) );

    while ( (character = CFStringGetCharacterFromInlineBuffer(&buf, i)) != 0 )
    {
        if ( [charset characterIsMember: character] )
            [set addIndex: i];

        i++;
    }

    return ( set );
}

This is better because it will grab a number of characters at once, fetching more as required. It's effectively the string-character version of for ( id x in y ) in ObjC 2.



来源:https://stackoverflow.com/questions/997079/objective-c-nsstring-problem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!