How do you check a string for white spaces in iOS?

How do you check a string for white spaces in iOS.  This issue recently crossed my plate.  In some programming languages you can check for white spaces using some sort of trim or similar function.  What if however you want to check the internals of a string for whitespaces, such as to ensure that there are no whitespaces inside a username or a password.

In iOS there is a handy little trick to figure this out quickly and easily.  In iOS you use the stringByReplacingOccurencesOfString. You replace and spaces with an empty replacement and then compare the string length value.  In the example below we have created a function which will return a BOOL value of YES or NO to ensure there are no spaces.

 (BOOL)ensureNoSpacesInText:(NSString *)stringValue {
   NSString *trimmed = [stringValue stringByReplacingOccurrencesOfString:@" " withString:@""];
   if ([trimmed length] < [stringValue length]) {
     //There were white spaces in the field... return false
     return NO;
   return YES;


Posted in , , and tagged .