3

How can I calculate the number of whitespaces in a String (e.g. "How are you?") in Objective-C?

Adil Hussain
  • 30,049
  • 21
  • 112
  • 147
varmab
  • 243
  • 1
  • 2
  • 5

2 Answers2

8

You could do this:

[[string componentsSeparatedByString:@" "] count]

Also, see this question for a couple of other solutions: Number of occurrences of a substring in an NSString?

Community
  • 1
  • 1
Anshu Chimala
  • 2,800
  • 2
  • 23
  • 22
1

If you want to just get the number of whitespaces between words, you can do [[string componentsSeparatedByString:@" "] count] - 1 (there will always be 1 less space than there are words).

However, that will only get the number of whitespaces between words, not the total number of spaces (i.e. " How are you ? " will 3 spaces, which is fine if that's what you need). If you want the total number of spaces in the string, though, go with looping through it.

NSUInteger spaces = 0;
for (NSUInteger index = 0; index < [string length]; index++) {
    if ([string characterAtIndex:index] == ' ') {
        spaces++;
    }
}

That will produce 11 for "_How__are_you___?___" (the code formatter deletes extra spaces in a line, so I had to show spaces with underscores).

Itai Ferber
  • 28,308
  • 5
  • 77
  • 83