从NSString中删除重复的单词并另存为新的NSString

use*_*452 3 objective-c nsstring nsmutablearray nsarray ios

我有一些场景,我可能有一个包含几个单词的NSString,其中一些是重复的.我想要做的是采取一个看起来像这样的字符串:

One Two Three Three Three Two Two Two One One Two Three
Run Code Online (Sandbox Code Playgroud)

并使它看起来像:

One Two Three
Run Code Online (Sandbox Code Playgroud)

可能有时候原始NSString的确切长度也不同.到目前为止我所拥有的是:

NSString *hereitis = @"First Second Third Second Third First First First";
    NSArray *words = [hereitis componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    NSCountedSet *countedSet = [NSCountedSet setWithArray:words];
    NSMutableArray *finalArray = [NSMutableArray arrayWithCapacity:[words count]];

for(id obj in countedSet) {
    if([countedSet countForObject:obj] == 1) {
        [finalArray addObject:obj];
    }
}
NSString *string = [finalArray componentsJoinedByString:@" "];
NSLog(@"String%@", string);
Run Code Online (Sandbox Code Playgroud)

但是,这只是在我的数组中返回String,而不是任何单词.

Mic*_*lum 11

实际上,这可以通过不那么轻松的方式完成.NSSet不允许重复条目.因此,您可以将字符串分解为数组,并使用该数组创建该集合.从那里,您所要做的就是转换回去,并且将删除欺骗.

NSString *inputString = @"One Two Three Three Three Two Two Two One One Two Three";
NSSet *aSet = [NSSet setWithArray:[inputString componentsSeparatedByString:@" "]];
NSString *outputString = [aSet.allObjects componentsJoinedByString:@" "];

NSLog(@"___%@___",outputString); // Outputs "___One Two Three___"
Run Code Online (Sandbox Code Playgroud)

  • +1无需复制`set`将为您提供的行为. (4认同)