0

I'm just wondering if there is a simpler way to find a substring within a string in Objective C.

My string is question is this: (messy I know...)

filename.cpp - line: 1 "comment 1"\nfilename.cpp - line: 1 "comment 2"\nfilename.cpp - line: 1 "comment 3"\n

So what I want to do is extract into an array all the bits between the quotation marks. I've been messing around with the componentsSeparatedByString method to try to manipulate the string enough to leave me with the "comments" but it just seems a very messy way to do it.

Thanks for any help!

2
  • 1
    Use NSRegularExpression. Commented Apr 20, 2013 at 17:49
  • 1
    Use NSScanner to parse the string or use rangeOfString to find the index of the quotes. Commented Apr 20, 2013 at 18:16

2 Answers 2

1

Maybe I don't understand your question precisely, but:
If your strings to be parsed always start with something not to be included, i.e. if the 1st substring to be extracted is not at the beginning of your string, you could use

NSMutableArray *components = [NSMutableArray arrayWithArray: [yourString componentsSeparatedByString:@"\""]];
for (int i=0; i<components.count; i++) {
   [components removeObjectAtIndex:i];
}
Sign up to request clarification or add additional context in comments.

Comments

0

You can use NSScanner to scan for \" and store every other substring in an array

NSString *string = @"filename.cpp - line: 1 \"comment 1\"\nfilename.cpp - line: 1 \"comment 2\"\nfilename.cpp - line: 1 \"comment 3\"\n";
NSScanner *scanner = [NSScanner scannerWithString:string];
NSMutableArray *array = [NSMutableArray array];

while (YES) {
    NSString *s;
    [scanner scanUpToString:@"\"" intoString:NULL];
    [scanner setScanLocation:[scanner scanLocation]+1];
    [scanner scanUpToString:@"\"" intoString:&s];
    if(s)
        [array addObject:s];
    if(![scanner isAtEnd])
        [scanner setScanLocation:[scanner scanLocation]+1];
    else break;
}

result:

array = (
    comment 1,
    comment 2,
    comment 3
)

Comments

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.