从NSString中删除所有重复的字符 [英] Remove all duplicate characters from NSString

查看:125
本文介绍了从NSString中删除所有重复的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How to do this using standard methods (without manual iteration through source string)?

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

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).

推荐答案

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

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

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

This results in the string "adbc" (duplicates removed) and the sorted array of unique characters ["a", "b", "c", "d"].

这篇关于从NSString中删除所有重复的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆