0

我想找到一个特定的单词并阅读相应的两行。

前任 :

苹果

xxxxxxxxxxxxxxxxxx

yyyyyyyyyyyyyyyyyy

三星

qqqqqqqqqqqqqqqq

wwwwwwwwwwwwwwww

诺基亚

tttttttttttttttt

zzzzzzzzzzzzzzzzz

如果我搜索“apple”,我想得到apple第二行也是 ( yyyyyyyy) 。我尝试使用下面的代码,但它不起作用:

NSString *contentString = [NSString stringWithContentOfFile:path/to/your/file.txt encoding:textEncoding error:&error];

if (!error) {
    NSRange range = [contentString rangeOfString:yourKeyword];

......
4

1 回答 1

0

以字符串形式获取文件,并用换行符分隔它。然后,找到您想要的行并获得接下来的两行。如果我想搜索Dian007,类似-

// for myfile.txt
NSString* path = [[NSBundle mainBundle] pathForResource:@"myfile" ofType:@"txt"];
NSString *content = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:NULL];
NSArray *myArray = [content componentsSeparatedByString:@"\n"];

// since we want two lines more, don't count last two elements
for(int i = 0; i < ([myArray count] - 2); ++i) { 
  if([[myArray objectAtIndex:i] isEqualToString:@"Dian007"]) {
    // get i-th, (i + 1)th and (i + 2)th lines here

    // For example, to print the lines...
    NSLog(@"first item := \"%@\"", [myArray objectAtIndex:i]);
    NSLog(@"second item := \"%@\"", [myArray objectAtIndex:(i + 1)]);
    NSLog(@"third item := \"%@\"", [myArray objectAtIndex:(i + 2)]);
  }
}
于 2012-10-15T14:08:36.900 回答