Remove all duplicate characters from NSString

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

PS: In the final, I want to get the sorted characters of the source string. I tried using NSCharacterSet, but cannot find a way to convert the character set to a string (without repeating the set).

+2
source share
1 answer

There is no built-in method for this, but it is quite easy to iterate over the characters of a string and create a new line 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:)]);

The result is a string "adbc"(duplicates removed) and a sorted array of unique characters ["a", "b", "c", "d"].

+3
source

Source: https://habr.com/ru/post/1598773/


All Articles