如何使用标准方法(不通过源字符串手动迭代)?
PS:在最后我想得到源字符串的有序字符。我尝试使用NSCharacterSet
,但找不到将字符集转换为字符串的方法(不迭代该集合)。
答案 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"]
。