Search code examples
objective-cnsstringnscharacterset

Comparing each character in an NSString against a collection of characters


My intent is to analyze the user's input from a text field and check if he used any symbols.

For example, user's input is "/ardv/*k" and I need a variable that says the user typed 3 symbols.

I do not understand how to use NSRange to search against a string, because it stops as soon as it finds the first occurrence.

Also, NSSet is not compatible with characterAtIndex selector.

isEqualTo: didn't work.

Here's what I did, but I want to know how I can make this code simpler if possible:

  ...
    NSString *testThisString = @"/ardv/*k";        
    NSCharacterSet *unknownFlags1 = [NSCharacterSet punctuationCharacterSet];
    NSCharacterSet *unknownFlags2 = [NSCharacterSet symbolCharacterSet];
    NSCharacterSet *unknownFlags3 = [NSCharacterSet whitespaceCharacterSet];

    int count = 0;
    for (int i = 0; i < [testThisString length]; i++) {
    if ([unknownFlags1 characterIsMember:[testThisString characterAtIndex:i]] |
   [unknownFlags2 characterIsMember:[testThisString characterAtIndex:i]] | 
   [unknownFlags3 characterIsMember:[testThisString characterAtIndex:i]]) {
        count++;
    }
}
    NSLog(@"There are %d unknowns", count);
  ...

Solution

  • To check if a string has any characters belonging to a set, you simply do this:

    NSString *testString = @"hello$%^";
    NSRange r = [testString rangeOfCharacterFromSet:[NSCharacterSet punctuationCharacterSet]];
    if (r.location != NSNotFound) {
        // the string contains a punctuation character
    }
    

    If you want to know all of the locations of the punctuation characters, just keep searching with a different input range. Something like:

    NSRange searchRange = NSMakeRange(0, [testString length]);
    while (searchRange.location != NSNotFound) {
        NSRange foundRange = [searchString rangeOrCharacterFromSet:[NSCharacterSet punctuationCharacterSet] options:0 range:searchRange];
        searchRange.location = foundRange.location + 1;
        searchRange.length = [testString length] - searchRange.location;
        if (foundRange.location != NSNotFound) {
            // found a character at foundRange.location
        }
    }