Boon
Boon

Reputation: 41490

What's the fastest way to find the number of spaces in an NSString?

I have an NSString and I want to find the number of spaces in it. What's the fastest way?

Upvotes: 3

Views: 100

Answers (3)

SSteve
SSteve

Reputation: 10728

I tried this and it seems to work. It might be possible to optimize, but you only need to worry about that if it's absolutely necessary.

NSUInteger spacesInString(NSString *theString) {
    NSUInteger result = 0;
    if ([theString length]) {
        const char *utfString = [theString UTF8String];
        NSUInteger i = 0;
        while (utfString[i]) {
            if (' ' == utfString[i]) {
                result++;
            }
            i++;
        }
    }

    return result;
}

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726629

Perhaps not the fastest to execute, but the fastest to type up:

[[myString componentsSeparatedByString:@" "] count]-1

Upvotes: 3

WrightsCS
WrightsCS

Reputation: 50707

I haven't tested this, but it seems like it should work off the top of my head.

int spacesCount = 0;

NSRange textRange;
textRange = [string rangeOfString:@" "];

if(textRange.location != NSNotFound)
{
    spacesCount = spacesCount++;
}

NSLog(@"Spaces Count: %i", spacesCount);

Upvotes: 0

Related Questions