Reputation: 41490
I have an NSString and I want to find the number of spaces in it. What's the fastest way?
Upvotes: 3
Views: 100
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
Reputation: 726629
Perhaps not the fastest to execute, but the fastest to type up:
[[myString componentsSeparatedByString:@" "] count]-1
Upvotes: 3
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