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.
            Asked
            
        
        
            Active
            
        
            Viewed 1,083 times
        
    3 Answers
3
            
            
        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] : @"";
 
    
    
        Sergey Kalinichenko
        
- 714,442
- 84
- 1,110
- 1,523
0
            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:@","];
 
    
    
        keen
        
- 3,001
- 4
- 34
- 59
- 
                    It would be nice if you added code for step two. Since everyone with a simillar problem probably dont know how to write it. – Jens Bergvall Aug 22 '13 at 11:07
- 
                    You could have googled it, and found it very easily. http://stackoverflow.com/questions/5978574/removing-duplicates-from-nsmutablearray and http://stackoverflow.com/questions/1025674/the-best-way-to-remove-duplicate-values-from-nsmutablearray-in-objective-c – keen Aug 22 '13 at 12:13
- 
                    - 1 Please add code for step two into the answer. You shouldn's assume people know, if that was the case you could assume everyone knows everything. Will add +1 when question is complete. – Jens Bergvall Aug 23 '13 at 07:26
0
            
            
        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;
 
    
    
        msmq
        
- 1,298
- 16
- 28
