`
renzhelife
  • 浏览: 668205 次
文章分类
社区版块
存档分类
最新评论

如何在一个已排序的NSArray中搜索某一特定字符串?答案是使用CFArray自带的搜索功能

 
阅读更多
如何在一个已排序的NSArray中搜索某一特定字符串?答案是使用CFArray自带的搜索功能:

NSMutableArray *sortedArray = [NSMutableArrayarrayWithObjects:@"Alice",@"Beth",@"Carol",@"Ellen",nil];
//Where is "Beth"?
unsignedindex = (unsigned)CFArrayBSearchValues((CFArrayRef)sortedArray,
CFRangeMake(0,CFArrayGetCount((CFArrayRef)sortedArray)),
(CFStringRef)@"Beth",
(CFComparatorFunction)CFStringCompare,
NULL);
if(index < [sortedArraycount])
{
NSLog(@"Beth was found at index %u", index);
}else{
NSLog(@"Beth was not found (index is beyond the bounds of sortedArray)");
}
//Where should we insert "Debra"?
unsignedinsertIndex = (unsigned)CFArrayBSearchValues((CFArrayRef)sortedArray,
CFRangeMake(0,CFArrayGetCount((CFArrayRef)sortedArray)),
(CFStringRef)@"Debra",
(CFComparatorFunction)CFStringCompare,
NULL);
[sortedArrayinsertObject:@"Debra"atIndex:insertIndex];
NSLog([sortedArraydescription]);

NSMutableArray *sortedArray = [NSMutableArrayarrayWithObjects:@"Alice",@"Beth",@"Carol",@"Ellen",nil];
//Where is "Beth"?
unsignedindex = (unsigned)CFArrayBSearchValues((CFArrayRef)sortedArray,
CFRangeMake(0,CFArrayGetCount((CFArrayRef)sortedArray)),
(CFStringRef)@"Beth",
(CFComparatorFunction)CFStringCompare,
NULL);
if(index < [sortedArraycount])
{
NSLog(@"Beth was found at index %u", index);
}else{
NSLog(@"Beth was not found (index is beyond the bounds of sortedArray)");
}
//Where should we insert "Debra"?
unsignedinsertIndex = (unsigned)CFArrayBSearchValues((CFArrayRef)sortedArray,
CFRangeMake(0,CFArrayGetCount((CFArrayRef)sortedArray)),
(CFStringRef)@"Debra",
(CFComparatorFunction)CFStringCompare,
NULL);
[sortedArrayinsertObject:@"Debra"atIndex:insertIndex];
NSLog([sortedArraydescription]);
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics