Search code examples
objective-ciosnsstringnscharacterset

compare characters from nsstring to different charactersets


I want to compare each character in an nsstring one by one to different nscharactersets and perform different operations according to the characterset it matches.

I'm able to assign each character to a substring for comparison using a for loop.

- (void) compareCharactersOfWord: (NSString *) word {

    for (int i = 0; i<[word length]; i++) {

        NSString *substring = [word substringWithRange:NSMakeRange(i,1)];


        //need to compare the substring to characterset here

    }
}

I also have my two charactersets

 setOne = [[NSCharacterSet characterSetWithCharactersInString:@"EAIONRTLSU"]invertedSet];

 setTwo = [[NSCharacterSet characterSetWithCharactersInString:@"DG"] invertedSet];

I'm a bit lost on the comparison part. I tried different methods like "rangeOfCharacterFromSet" but I kept getting erros. in pseudocode I would need something like

if (setOne containsCharacterFrom substring) {

//do stuff here

} else if (setTwo containsCharacterFrom substring) {

//do other stuff here

}

Solution

  • 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
        }
    }
    

    There one big limitation to the second option. It doesn't work with Unicode characters higher than 0xFFFF.