2

如何使用标准方法(无需通过源字符串手动迭代)来做到这一点?

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

4

1 回答 1

4

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

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"]

于 2012-06-22T08:34:44.950 回答