Friday, June 14, 2013

NSCharacterSet characterSetWithCharactersInString example in Objective C (iOS).

NSCharacterSet characterSetWithCharactersInString

Returns a character set containing the characters in a given string.

+ (id)characterSetWithCharactersInString:(NSString *)aString

A string containing characters for the new character set.

Return Value of [NSCharacterSet characterSetWithCharactersInString]
A character set containing the characters in aString. Returns an empty character set if aString is empty.

NSCharacterSet characterSetWithCharactersInString example.
You can create your own character set:

NSCharacterSet *s = [NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_"];
Once you have that, you invert it to everything that's not in your original string:

s = [s invertedSet];
And you can then use a string method to find if your string contains anything in the inverted set:

NSRange r = [string rangeOfCharacterFromSet:s];
if (r.location != NSNotFound) {
  NSLog(@"the string contains illegal characters");

Example of [NSCharacterSet characterSetWithCharactersInString].
NSString *originalString = @"(123) 123123 abc";
NSMutableString *strippedString = [NSMutableString

NSScanner *scanner = [NSScanner scannerWithString:originalString];
NSCharacterSet *numbers = [NSCharacterSet

while ([scanner isAtEnd] == NO) {
  NSString *buffer;
  if ([scanner scanCharactersFromSet:numbers intoString:&buffer]) {
    [strippedString appendString:buffer];

  } else {
    [scanner setScanLocation:([scanner scanLocation] + 1)];

NSLog(@"%@", strippedString); // "123123123"

NSCharacterSet characterSetWithCharactersInString example.
NSString* string = @"ABCCDEDRFFED";
NSCharacterSet* characters = [NSCharacterSet characterSetWithCharactersInString:@"ABC"];
NSUInteger characterCount;

NSUInteger i;
for (i = 0; i < [yourString length]; i++) {
  unichar character = [yourString characterAtIndex:i];
  if ([characters characterIsMember:character]) characterCount++;

NSLog(@"Total characters = %d", characterCount);

End of NSCharacterSet characterSetWithCharactersInString example article.