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

2 Answers 2

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);  
}
Sign up to request clarification or add additional context in comments.

6 Comments

thank you - i'll try this out. Is there any advantage/disadvantage from xingzhi.sg's example? just curious.
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
imageKey must be iOS specific?; I'm try to create this for OS X, is there an equivalent for that?
sorry imageKey was a local variable in my project. i edited my answer it should be your local variable fileContentsString
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?
|
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.

2 Comments

I get an error on NSString * wordAfterFoo = captures[1]; -- Subscript requires size of interface NSArray, which is not constant in non-fragile ABI
oops... should be [captures objectAtIndex:1];

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.