开发者

Why binary search not find my string?

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:NSStringEncodingConversionA开发者_StackOverflow中文版llowLossy 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?


The problem is in the way you read in the array. If you replace the code that assigns LineCount with

NSArray * LinesCount = [NSArray arrayWithObjects:@"aaa", @"bbb", @"ccc", @"ddd", @"eee", nil];

you will see the binary search performs fine.

There are two issues in your code:

  • Line separator is probably just "\n" if the file has been created on Mac OS X
  • Your array will contain a left over "" as it's last element hence the requirement for ordering as required by CFArrayBSearchValues is no longer satisfied.

As an example:

 NSLog(@"%@", [@"one\ntwo\n" componentsSeparatedByString:@"\n"]);

yields (note the last empty element):

 2011-09-29 16:52:33.024 a.out[4019:707] (
     one,
     two,
     ""
 )
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜