简体   繁体   中英

Compare two strings and remove common elements

I have two comma seperated NSString 's & I want to remove the similar characters from first string only.

ex. str1 = 0,1,2,3
    str2 = 1,2.
    output -> str1 = 0,3 and str2 = 1,2.

I have one option that, seperate both the string with comma seperated values in a array. But it requires two NSArray 's & apply loop and then remove the common elements, but it is very tedious job. So I want some simple & proper solution which avoid the looping.

kindly help me to sort out this.

Try this one:

No loop is required!!!

You have got all the required APIs.

NSString *str1=@"0,1,2,3";
NSString *str2=@"1,2";

NSMutableArray *arr1=[[NSMutableArray alloc]initWithArray:[str1 componentsSeparatedByString:@","]];

[arr1 removeObjectsInArray:[str2 componentsSeparatedByString:@","]];
NSLog(@"arr1 %@",arr1);
/*
NSMutableString *finalString=[NSMutableString new];

for (NSInteger i=0; i<[arr1 count]; i++) {
    NSString *str=[arr1 objectAtIndex:i];

    [finalString appendString:str];
    if (i!=[arr1 count]-1) {
      [finalString appendString:@","];  
    }
}
*/
NSString *finalString=[arr1 componentsJoinedByString:@","];
NSLog(@"finalString %@",finalString);

Something like that ?

 NSString *string = @"0,1,2,3";
 NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self like '1' OR self like '2'"];
 NSLog(@"%@",[[string componentsSeparatedByString:@","] filteredArrayUsingPredicate:predicate]);
    id str1=@"aa,ab,ac,cd,ce,cf";
    id str2=@"aa,ac,cd,cf";
    //no ab and no ce

    id cmps1 = [str1 componentsSeparatedByString:@","];
    id cmps2 = [str2 componentsSeparatedByString:@","];        

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"NOT SELF IN %@", cmps2];
    NSArray *final = [cmps1 filteredArrayUsingPredicate:predicate]; 
    id str = [final componentsJoinedByString:@","];
    NSLog(@"%@", str);

The only solution that I can think of would be this:

NSMutableArray* arr1 = [str1 componentsSeparatedByString:@","] mutableCopy];
NSArray* arr2 = [str2 componentsSeparatedByString:@","];
for (NSString* str in arr2) {
  [arr1 removeObject:str];
}
NSString* newString1 = [arr1 componentsJoinedByString:@","];

Is this what you tried? If "str1" looks something like "1,1,2,2,2", then you might have some more work to do here to get rid of the duplicates. But that's basically it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM