Friday, June 14, 2013

NSCharacterSet whitespaceCharacterSet example in Objective C (iOS).


NSCharacterSet whitespaceCharacterSet

Returns a character set containing only the in-line whitespace characters space (U+0020) and tab (U+0009).

+ (id)whitespaceCharacterSet

Return Value
A character set containing only the in-line whitespace characters space (U+0020) and tab (U+0009).

Discussion of [NSCharacterSet whitespaceCharacterSet]
This set doesn’t contain the newline or carriage return characters.

NSCharacterSet whitespaceCharacterSet example.
NSString *theString = @"    Hello      this  is a   long       string!   ";

NSCharacterSet *whitespaces = [NSCharacterSet whitespaceCharacterSet];
NSPredicate *noEmptyStrings = [NSPredicate predicateWithFormat:@"SELF != ''"];

NSArray *parts = [theString componentsSeparatedByCharactersInSet:whitespaces];
NSArray *filteredArray = [parts filteredArrayUsingPredicate:noEmptyStrings];
theString = [filteredArray componentsJoinedByString:@" "];

Example of [NSCharacterSet whitespaceCharacterSet].
There is method for that in NSString class. Check stringByTrimmingCharactersInSet:(NSCharacterSet *)set. You should use [NSCharacterSet whitespaceCharacterSet] as parameter:

NSString *foo = @" untrimmed string ";
NSString *trimmed = [foo stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

NSCharacterSet whitespaceCharacterSet example.
- (NSString *)stringByTrimmingLeadingWhitespace {
    return [self stringByTrimmingLeadingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
}

- (NSString *)stringByTrimmingTrailingWhitespace {
    return [self stringByTrimmingTrailingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
}

- (NSString *)stringByTrimmingLeadingWhitespaceAndNewline {
    return [self stringByTrimmingLeadingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}

- (NSString *)stringByTrimmingTrailingWhitespaceAndNewline {
    return [self stringByTrimmingTrailingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}

End of NSCharacterSet whitespaceCharacterSet example article.