2

我有两个逗号分隔NSString的 & 我只想从第一个字符串中删除相似的字符。

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

我有一个选择,即在数组中用逗号分隔值分隔两个字符串。但它需要两个NSArray& 应用loop然后删除共同的元素,但这是一个非常繁琐的工作。所以我想要一些简单而适当的解决方案来避免循环。

请帮我解决这个问题。

4

4 回答 4

6

试试这个:

不需要循环!!!

您已获得所有必需的 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);
于 2012-12-19T14:16:39.817 回答
0

类似的东西?

 NSString *string = @"0,1,2,3";
 NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self like '1' OR self like '2'"];
 NSLog(@"%@",[[string componentsSeparatedByString:@","] filteredArrayUsingPredicate:predicate]);
于 2012-12-19T14:12:54.737 回答
0
    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);
于 2012-12-19T14:15:07.007 回答
0

我能想到的唯一解决方案是:

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

这是你试过的吗?如果“str1”看起来像“1,1,2,2,2”,那么您可能需要做更多的工作来消除重复项。但基本上就是这样。

于 2012-12-19T14:15:50.387 回答