Remove all duplicate characters from NSString

烂漫一生 提交于 2019-12-06 12:00:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!