Friday, June 14, 2013

NSCharacterSet characterIsMember example in Objective C (iOS).


NSCharacterSet characterIsMember

Returns a Boolean value that indicates whether a given character is in the receiver.

- (BOOL)characterIsMember:(unichar)aCharacter

Parameters
aCharacter
The character to test for membership of the receiver.

Return Value of [NSCharacterSet characterIsMember]
YES if aCharacter is in the receiving character set, otherwise NO.

NSCharacterSet characterIsMember example.
To eliminate non letters:

NSString *letters = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
NSCharacterSet *notLetters = [[NSCharacterSet characterSetWithCharactersInString:letters] invertedSet];
NSString *newString = [[string componentsSeparatedByCharactersInSet:notLetters] componentsJoinedByString:@""];
To check one character at a time:

for (int i = 0; i < [string length]; i++) {
    unichar c = [string characterAtIndex:i];
    if ([notLetters characterIsMember:c]) {
       ...
    }
}

Example of [NSCharacterSet characterIsMember].
To see if your 'substring' variable in one of your sets you would do:

if ([substring rangeOfCharacterFromSet:setOne].location != NSNotFound) {
    // substring is in setOne
} else if ([substring rangeOfCharacterFromSet:setTwo].location != NSNotFound) {
    // substring is in setTwo
}
Another option is to work with characters.

for (int i = 0; i<[word length]; i++) {
    unichar ch = [word characterAtIndex:i];

    if ([setOne characterIsMember:ch]) {
        // in setOne
    } else if ([setTwo characterIsMember:ch]) {
        // in setTwo
    }
}

NSCharacterSet characterIsMember example.
- (BOOL) textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString*)textEntered
{
    for (int i = 0; i < [textEntered length]; i++)
    {
        unichar c = [textEntered characterAtIndex:i];
        if ([disallowedCharacters characterIsMember:c])
        {
            return NO;
        }
    }
    return YES;
}

End of NSCharacterSet characterIsMember example article.