2

How to do this using standard methods (without manual iteration through source string)?

PS: At final I want to get sorted characters of source string. I tried to use NSCharacterSet, but can't find a method to convert character set to string (without iterating the set).

brigadir
  • 6,874
  • 6
  • 46
  • 81

1 Answers1

4

There is no built-in method for this, but it's pretty easy to iterate over the characters of the string and build a new string without duplicates:

NSString *input = @"addbcddaa";
NSMutableSet *seenCharacters = [NSMutableSet set];
NSMutableString *result = [NSMutableString string];
[input enumerateSubstringsInRange:NSMakeRange(0, input.length) options:NSStringEnumerationByComposedCharacterSequences usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
    if (![seenCharacters containsObject:substring]) {
        [seenCharacters addObject:substring];
        [result appendString:substring];
    }
}];
NSLog(@"String with duplicate characters removed: %@", result);
NSLog(@"Sorted characters in input: %@", [seenCharacters.allObjects sortedArrayUsingSelector:@selector(compare:)]);

This results in the string "adbc" (duplicates removed) and the sorted array of unique characters ["a", "b", "c", "d"].

omz
  • 53,243
  • 5
  • 129
  • 141