Question

How can I remove duplicated substings from string? For ex. I have: aaa,bbb,ttt,bbb,rrr. And in result I want to have aaa,bbb,ttt,rrr (deleted duplicated bbb). I hope for your help. Thanks.

Était-ce utile?

La solution 2

Do it in three steps

1) NSArray *items = [theString componentsSeparatedByString:@","];

2) remove duplicate element from array

    NSArray* array =  [NSArray arrayWithObjects:@"test1", @"test2", @"test1", @"test2",@"test4",   nil];

    NSArray* filteredArray = [[NSArray alloc] init];
    NSSet *set= [NSOrderedSet orderedSetWithArray:array];
    filteredArray = [set allObjects];

3) Concate String from array

NSString *myString = [myArray componentsJoinedByString:@","];

Autres conseils

You can do it like this:

NSMutableSet *seen = [NSMutableSet set];
NSMutableString *buf = [NSMutableString string];
for (NSString *s in [str componentsSeparatedByString:@","]) {
    if (![seen containsObject:s]) {
         [seen add:s];
         [buf appendFormat:@",%@", s];
    }
}
NSString *res = [buf length] ? [buf substringFromIndex:1] : @"";

You can use NSMutableDictionary; In dictionary there are two elements; 1. Key 2. Value

Just set Keys as your array elements; Special point is that 'Key' can't be duplicate;

Now just get array of Keys by using [dictionary allKeys];

Now, at this stage you have unique values in new array;

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top