Friday, June 14, 2013

NSCharacterSet invertedSet example in Objective C (iOS).

NSCharacterSet invertedSet

Returns a character set containing only characters that don’t exist in the receiver.

- (NSCharacterSet *)invertedSet

Return Value
A character set containing only characters that don’t exist in the receiver.

Discussion of [NSCharacterSet invertedSet]
Inverting an immutable character set is much more efficient than inverting a mutable character set.

NSCharacterSet invertedSet example.
NSMutableCharacterSet *mcs = [[[NSCharacterSet letterCharacterSet] invertedSet] mutableCopy];
[mcs removeCharactersInString:@"<characters you want excluded>"];

myString = [[myString componentsSeparatedByCharactersInSet:mcs] componentsJoinedByString:@""];

[mcs release];

Example of [NSCharacterSet invertedSet].
NSMutableCharacterSet *charactersToKeep = [NSMutableCharacterSet alphanumericCharacterSet];
[charactersToKeep addCharactersInString:@" ,."];

NSCharacterSet *charactersToRemove = [charactersToKeep invertedSet];

NSString *trimmedReplacement = [[ str componentsSeparatedByCharactersInSet:charactersToRemove] componentsJoinedByString:@"" ];

NSCharacterSet invertedSet example.
NSCharacterSet * set = [[NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLKMNOPQRSTUVWXYZ0123456789"] invertedSet];

if ([aString rangeOfCharacterFromSet:set].location != NSNotFound) {
  NSLog(@"This string contains illegal characters");
You could also use a regex (this syntax is from RegexKitLite: ):

if ([aString isMatchedByRegex:@"[^a-zA-Z0-9]"]) {
  NSLog(@"This string contains illegal characters");

End of NSCharacterSet invertedSet example article.