2012-09-09 51 views
0

我有一个字符串数组(多于5k个元素),每个字符串长度都是可变的。我可以使用NSPredicate在数组中找到特定的字符串(花了一点时间来弄清楚)。现在我需要找到长度大于N的元素。创建一个NSPredicate来查找长度大于N的元素。

我已阅读文档,并且长度似乎不是“谓词编程指南”中可用的功能之一。

在此先感谢。

Imagmast

+0

为什么这是低票?我认为用评论解释你的倒票是很好的举止。我猜这是因为这个问题没有发布代码尝试?一个更有建设性的回应(特别是经验分数相对较低)将是要求他发布他的字符串匹配代码。除非有人提供-1的充分理由,否则我的+1。 – danh

回答

2
NSArray * words= [allLinedStrings filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"length > %d",N]]; 

N是你的整数,正如你在你的问题中提到的那样。

+0

谢谢。有用。你能分享链接到其他谓词“功能”吗? – Larry

-1

我不熟悉NSPredicate,所以我不能给你使用它的解决方案,但不能你只需要使用一些纯的NSString方法:

//This is the length of the string you want to check 
int threshold = 5; 

//Iterates through all elements in the array 
for(int index = 0; index < [stringArray count]; index++) { 

    //Checks if the length of the string stored at the current index is greater than N 
    if([[stringArray objectAtIndex:index] length] > threshold) { 

     //String length is greater than N 
    } 
} 

可选,你可以在检查中添加,以查看阵列只有通过更换这条线串(为了安全牺牲性能):

if([[stringArray objectAtIndex:index] length] > threshold) 

有了这个:

if([[stringArray objectAtIndex:index] length] > threshold && [[stringArray objectAtIndex:index] isKindOfClass[NSString class]]) 

这样做是为了确保当前索引处的对象是NSString。如果不是,则会收到运行时错误。

+0

在调用'length'之前检查课程。 – Willeke