Search code examples
objective-cnsscanner

Extra characters in NSScanner (objective-C)


I have a small problem parsing a string in NSScanner. I've read other SO posts on this, but cannot solve this dumb issue.

I have a string like this "the first word is not = to the second word"

My code is:

NSString *seperator = @" =";
NSCharacterSet *newLineCharacterSet = [NSCharacterSet newlineCharacterSet];


[scanner scanUpToString:seperator intoString:&firstString];
[scanner scanString:seperator intoString:NULL];
scanPosition = [scanner scanLocation];
//scanPosition = scanPosition +2;

secondString = [[scanner string] substringFromIndex:scanPosition];

[scanner scanUpToCharactersFromSet:newLineCharacterSet intoString:&secondString];

NSLog(@"firstString: %@", firstString);
NSLog(@"secondString: %@", secondString);

The problem is that I'm getting the separator as part of the secondString.

firstString: "the first word is not"
secondString is "= to the second word"      

Solution

  • Here's what I ran in Xcode:

    NSString *seperator = @" =";
    NSCharacterSet *newLineCharacterSet = [NSCharacterSet newlineCharacterSet];
    
    NSScanner *scanner = [NSScanner localizedScannerWithString:@"the first word is not = to the second word"];
    
    //NSString *firstString; //= @"the first word is not = to the second word";
    NSString *secondString;
    int scanPosition;
    NSString *foundSubs;
    
    [scanner scanUpToString:seperator intoString:&foundSubs];
    //[scanner scanString:seperator intoString:NULL];
    scanPosition = [scanner scanLocation];
    //scanPosition = scanPosition +2;
    
    secondString = [[scanner string] substringFromIndex:scanPosition+[seperator length]];
    
    //[scanner scanUpToCharactersFromSet:newLineCharacterSet intoString:&secondString];
    
    NSLog(@"firstString: %@", foundSubs);
    NSLog(@"secondString: %@", secondString);
    

    And got:

    2014-08-11 11:56:10.495 tester[3068:60b] firstString: the first word is not
    2014-08-11 11:56:10.496 tester[3068:60b] secondString:  to the second word
    

    For the sake of posterity check 'seperator' spelling