问题描述
- 比较两个字符串,删除评论元素
-
有两个用逗号分开的NSString
,我想要移除第一个字符重复的字符。ex. str1 = 0,1,2,3 str2 = 1,2. output -> str1 = 0,3 and str2 = 1,2.
有一种办法是,用逗号分开两个字符串,但是需要两个NSArray和LOOP循环,然后移除评论元素,但是这样实现起来非常困难,有没有简单办法实现?谢谢好心人帮忙。
解决方案
可以不用循环
但是需要设置好所有的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);
解决方案二:
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);
时间: 2024-11-05 16:25:25