为什么二分查找找不到我的字符串?
我有一个像这样的有序txt文件:
aaa
bbb
ccc
ddd
eee
我想检查文件中是否存在“ddd”字符串...
这里是我的函数:
- (BOOL) asd:(NSString*)sting
{
NSArray *LinesCount =
[[NSString stringWithContentsOfFile:@"longfile.txt"
encoding:NSStringEncodingConversionAllowLossy error:nil]
componentsSeparatedByString:@"\r\n"];
unsigned index = (unsigned)CFArrayBSearchValues(
(CFArrayRef)LinesCount,
CFRangeMake(0, CFArrayGetCount((CFArrayRef)LinesCount)),
(CFStringRef)string,
(CFComparatorFunction)CFStringCompare,
NULL);
if (index < [LinesCount count]) return YES;
return NO;
}
为什么它总是返回NO,对于任何字符串?
I have an ordered txt file like this:
aaa
bbb
ccc
ddd
eee
I want to check if "ddd" string exists in the file...
Here my func:
- (BOOL) asd:(NSString*)sting
{
NSArray *LinesCount =
[[NSString stringWithContentsOfFile:@"longfile.txt"
encoding:NSStringEncodingConversionAllowLossy error:nil]
componentsSeparatedByString:@"\r\n"];
unsigned index = (unsigned)CFArrayBSearchValues(
(CFArrayRef)LinesCount,
CFRangeMake(0, CFArrayGetCount((CFArrayRef)LinesCount)),
(CFStringRef)string,
(CFComparatorFunction)CFStringCompare,
NULL);
if (index < [LinesCount count]) return YES;
return NO;
}
Why does it always returns NO, with any string?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题在于您读取数组的方式。
如果您替换分配
LineCount
的代码,您将看到二分搜索执行良好。
您的代码中有两个问题:
举个例子:
产量(注意最后一个空元素):
The problem is in the way you read in the array.
If you replace the code that assigns
LineCount
withyou will see the binary search performs fine.
There are two issues in your code:
As an example:
yields (note the last empty element):