0

I know there are a few different ways to find text in file, although I haven't found a way to return the text after the string I'm searching for. For example, if I was to search file.txt for the term foo and wanted to return bar, how would I do that without knowing it's bar or the length?

Here's the code I'm using:

if (!fileContentsString) {
    NSLog(@"Error reading file");
}

// Create the string to search for
NSString *search = @"foo";

// Search the file contents for the given string, put the results into an NSRange structure
NSRange result = [fileContentsString rangeOfString:search];

// -rangeOfString returns the location of the string NSRange.location or NSNotFound.
if (result.location == NSNotFound) {
    // foo not found. Bail.
    NSLog(@"foo not found in file");
    return;
}
// Continue processing
NSLog(@"foo found in file");    
}
Joe Habadas
  • 628
  • 8
  • 21

2 Answers2

1

You might want to use RegexKitLite and perform a regex look up:

NSArray * captures = [myFileString componentsMatchedByRegex:@"foo\\s+(\\w+)"];
NSString * wordAfterFoo = captures[1];

Not test though.

xingzhi.sg
  • 423
  • 4
  • 10
1

you could use [NSString substringFromIndex:]

if (result.location == NSNotFound) 
{
    // foo not found. Bail.
    NSLog(@"foo not found in file");
    return;
}    
else    
{
    int startingPosition = result.location + result.length;
    NSString* foo = [fileContentsString substringFromIndex:startingPosition]        
    NSLog(@"found foo = %@",foo);  
}
JeanLuc
  • 4,783
  • 1
  • 33
  • 47
  • thank you - i'll try this out. Is there any advantage/disadvantage from xingzhi.sg's example? just curious. – Joe Habadas Jul 16 '12 at 07:12
  • my solution is easier for that task (especially if you're not familiar with regex). AND it just needs iOS 2.0 or OS X 10.0, so you don't need to carry an extra library with your project – JeanLuc Jul 16 '12 at 07:53
  • `imageKey` must be iOS specific?; I'm try to create this for OS X, is there an equivalent for that? – Joe Habadas Jul 16 '12 at 08:11
  • sorry `imageKey` was a local variable in my project. i edited my answer it should be your local variable `fileContentsString` – JeanLuc Jul 16 '12 at 10:04
  • okay, I understand. The problem now is that anything after `bar` is shown also. for example `foo bar is the string` will result in `bar is the string`. how do I only show `bar`? – Joe Habadas Jul 16 '12 at 16:47
  • search in the new string for first occurence of space and extract the first part. if there is no space, you already have your desired string. – JeanLuc Jul 16 '12 at 19:49