Alan
Alan

Reputation: 1275

Objective C NSString problem

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?

Upvotes: 2

Views: 3840

Answers (2)

Jim Dovey
Jim Dovey

Reputation: 11156

-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.

Upvotes: 4

James Eichele
James Eichele

Reputation: 119214

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
}

Upvotes: 6

Related Questions