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

时间:2014-06-26 17:31:15

标签: ios objective-c nsstring nsmutablearray nsarray

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

One Two Three Three Three Two Two Two One One Two Three

并使它看起来像:

One Two Three

有时候原始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);

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

3 个答案:

答案 0 :(得分: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___"

答案 1 :(得分:0)

然后你会得到一个字符串数组

for(id obj in countedSet) {
    if([countedSet countForObject:obj] == 1) {
        [finalArray addObject:obj];
    }
}

之后你可以用你的话

NSLog(@"%@", finalArray[0]); //log 'One'

答案 2 :(得分:0)

您也可以使用KVC Collection Operators

NSString *string = @"One Two Three Three Three Two Two Two One One Two Three";
NSArray *items = [string componentsSeparatedByString:@" "];
NSArray *uniqueItems = [items valueForKeyPath:@"@distinctUnionOfObjects.self"];
相关问题