pmerino
pmerino

Reputation: 6110

How to use NSScanner to scan from a string

I have a string which looks like:

#chat :hi there

And I'd like to scan all the text from the : to a string, so it ends like hi there

I've tried

[[NSScanner scannerWithString:argument] scanUpToString:@":" intoString:&newarg];

But newarg contains only #chat. How this can be achieved?

Upvotes: 1

Views: 6245

Answers (2)

samuelb
samuelb

Reputation: 43

Consider using an if statement to iterate through the scan. You've always told the computer to scan everything until the character ":", but it sounds like you actually want to scan everything AFTER the ":" character. Anne's answer provides an excellent example of such.

Upvotes: 0

Anne
Anne

Reputation: 27073

Example String:

#chat :Hello World,
#chat :How are you doing?

Code:

NSString *theString =   @"#chat :Hello World,\n"
                         "#chat :How are you doing?";

NSScanner *theScanner = [NSScanner scannerWithString:theString];
NSCharacterSet *seperator = [NSCharacterSet characterSetWithCharactersInString:@":"];
NSCharacterSet *newLine = [NSCharacterSet newlineCharacterSet];
NSString *theText;

while ([theScanner isAtEnd] == NO) {

    [theScanner scanUpToCharactersFromSet:seperator intoString:NULL];
    [theScanner setScanLocation: [theScanner scanLocation]+1];
    [theScanner scanUpToCharactersFromSet:newLine intoString:&theText];

    NSLog(@"%@",theText);

}

Output:

Hello World,
How are you doing?

Upvotes: 4

Related Questions