【发布时间】:2013-05-31 08:21:02
【问题描述】:
我有一个包含字符串的数组。其中一些字符串可能为空 (@"")。谓词必须是什么样子才能过滤数组并返回一个仅包含非空字符串的新数组:
数组 A: {"A","B","","D"} -> 过滤器 -> 数组 B: {"A","B","D"}
它也应该返回这个:
数组 A:{"","","",""} -> 过滤器 -> 数组 B:{}
【问题讨论】:
标签: ios objective-c nsarray nspredicate
我有一个包含字符串的数组。其中一些字符串可能为空 (@"")。谓词必须是什么样子才能过滤数组并返回一个仅包含非空字符串的新数组:
数组 A: {"A","B","","D"} -> 过滤器 -> 数组 B: {"A","B","D"}
它也应该返回这个:
数组 A:{"","","",""} -> 过滤器 -> 数组 B:{}
【问题讨论】:
标签: ios objective-c nsarray nspredicate
如果您只过滤NSStrings 的数组,请使用谓词SELF != ''。这匹配每个不完全等于空字符串的NSString。
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF != ''"];
NSArray *filteredArray = [array filteredArrayUsingPredicate:predicate];
示例代码:
NSArray *array = @[@"A", @"B", @"", @"C", @"", @"D"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF != ''"];
NSArray *filteredArray = [array filteredArrayUsingPredicate:predicate];
NSLog(@"Input array: %@\nFiltered array: %@", [array componentsJoinedByString:@","], [filteredArray componentsJoinedByString:@","]);
给出这个输出
Input array: A,B,,C,,D
Filtered array: A,B,C,D
编辑:Joris Kluivers 发布了谓词格式 length > 0 的解决方案。这可能是仅用于删除空字符串的更好解决方案,因为它可能会更快。
【讨论】:
检查字符串的长度:
NSArray *values = @[@"A", @"B", @"", @"D"];
NSPredicate *filterPredicate = [NSPredicate predicateWithFormat:@"length > 0"];
NSArray *filteredValues = [values filteredArrayUsingPredicate:filterPredicate];
在所需的数组("A", "B", "C")中得到结果
【讨论】:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF beginswith[c]%@",searchText];
[arrSearched removeAllObjects];
[arrSearched addObjectsFromArray:[self.arrContent filteredArrayUsingPredicate:predicate]];
这里 arrContent 是原始数组,arrSearched 是搜索后的输出数组。
【讨论】: