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");
}
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);
}