[英]Searching for a string within an array for an NSRange
我正在尝试在数组中搜索字符串,但是我只想在数组的最后五个对象中搜索该字符串。
我一直在摆弄我可以在NSRange上找到的每个参数,但无济于事。
我会发布一些示例代码,但是无论是通过自省,枚举还是只是我错过的一些NSRange调用,我什至都无法脱颖而出。
如果数组元素是要搜索的字符串,则可以按照以下方式直接检查数组:
if ([yourArray containsObject:yourString])
{
int index = [yourArray indexOfObject:yourString];
if (index>= yourArray.count-5)
{
// Your string matched
}
}
尝试这个 :-
//Take only last 5 objects
NSRange range = NSMakeRange([mutableArray1 count] - 5, 5);
NSMutableArray *mutableArray2 = [NSMutableArray arrayWithArray:
[mutableArray1 subarrayWithRange:range]];
//Now apply search logic on your mutableArray2
for (int i=0;i<[mutableArray2 count];i++)
{
if ([[mutableArray2 objectAtIndex:i] isEqualToString:matchString])
{
//String matched
}
}
希望这对您有所帮助!
我indexesOfObjectsWithOptions:passingTest:
喜欢indexesOfObjectsWithOptions:passingTest:
。 例:
NSArray *array = @[@24, @32, @126, @1, @98, @16, @67, @42, @44];
// run test block on each element of the array, starting at the end of the array
NSIndexSet *hits = [array indexesOfObjectsWithOptions:NSEnumerationReverse passingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
// if we're past the elements we're interested in
// we can set the `stop` pointer to YES to break out of
// the enumeration
if (idx < [array count] - 5) {
*stop = YES;
return NO;
}
// do our test -- if the element matches, return YES
if (40 > [obj intValue]) {
return YES;
}
return NO;
}];
// indexes of matching elements are in `hits`
NSLog(@"%@", hits);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.