如何在文本中找到一个单词并阅读相应的两行?

时间:2021-01-12 20:22:20

I would like to find a specific word and read the corresponding two lines.

我想找一个具体的单词并阅读相应的两行。

EX :

apple

xxxxxxxxxxxxxxxxxx

yyyyyyyyyyyyyyyyyy

samsung

qqqqqqqqqqqqqqqq

wwwwwwwwwwwwwwww

nokia

ttttttttttttttttt

zzzzzzzzzzzzzzzzz

If I search for "apple" I would like to get apple and the second line also (yyyyyyyy) . I tried with the code below but it's not working :

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

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

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

......

1 个解决方案

#1


0  

Get the file in a string, and separate it with newlines. Then, find the line you want and get the next two lines too. If I want to search for Dian007, something like-

获取字符串中的文件,并将其与换行符分开。然后,找到你想要的线,并获得接下来的两行。如果我想搜索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)]);
  }
}

#1


0  

Get the file in a string, and separate it with newlines. Then, find the line you want and get the next two lines too. If I want to search for Dian007, something like-

获取字符串中的文件,并将其与换行符分开。然后,找到你想要的线,并获得接下来的两行。如果我想搜索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)]);
  }
}