简体   繁体   English

比较两个字符串并删除常见元素

[英]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. 我有两个逗号分隔的NSString ,我只想从第一个字符串中删除相似的字符。

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. 但是它需要两个NSArray的&apply loop ,然后删除公共元素,但这是非常繁琐的工作。 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. 您已经拥有所有必需的API。

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. 如果“ str1”看起来像“ 1,1,2,2,2”,那么您可能需要做更多的工作来消除重复项。 But that's basically it. 但是基本上就是这样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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