从NSString中删除所有重复的字符

时间:2012-06-22 08:12:26

标签: objective-c nsstring duplicate-removal

如何使用标准方法(不通过源字符串手动迭代)?

PS:在最后我想得到源字符串的有序字符。我尝试使用NSCharacterSet,但找不到将字符集转换为字符串的方法(不迭代该集合)。

1 个答案:

答案 0 :(得分:3)

没有内置的方法,但迭代字符串的字符并构建一个没有重复的新字符串非常容易:

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:)]);

这会导致字符串"adbc"(删除重复项)和排序的唯一字符数组["a", "b", "c", "d"]