iosobjective-cstringnsstringnscountedset

Check IF one String contains the same characters as another string


I am trying to write a function which will allow me to determine whether one NSString* contains the characters of another NSString*. As an example, refer to the below scenario:

NSString *s1 = @"going";
NSString *s2 = @"ievngcogdl";

So essentially when the comparison between these 2 strings occurs, it should return true as the first string s1 has the same characters of the second string s2. Could I use an NSCountedSet? I know that this class has a method containsObject:(id) although I don't think that will solve my problem. Is there any other ways in completing this function and provide me the required results?


Solution

  • I think this method could be rather slow, but I would still favour it over [NSString rangeOfCharacterFromSet:], which requires creating an NSCharacterSet object per comparison:

    - (BOOL)string:(NSString *)string containsAllCharactersInString:(NSString *)charString {
        NSUInteger stringLen = [string length];
        NSUInteger charStringLen = [charString length];
        for (NSUInteger i = 0; i < charStringLen; i++) {
            unichar c = [charString characterAtIndex:i];
            BOOL found = NO;
            for (NSUInteger j = 0; j < stringLen && !found; j++)
                found = [string characterAtIndex:j] == c;
            if (!found)
                return NO;
        }
        return YES;
    }