问题
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).
回答1:
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"]
.
来源:https://stackoverflow.com/questions/11152459/remove-all-duplicate-characters-from-nsstring