0

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"      
ICL1901
  • 7,632
  • 14
  • 90
  • 138

2 Answers2

1

So you want to separate the strings? You can use NSString's componentsSeparatedByString method.

NSArray* foo = [@"the first word is not = to the second word" componentsSeparatedByString: @"="];

NSString *firstString = foo[0]; //the first word is not 
NSString *secondString = foo[1]; // to the second word

If you want to use the scanner you will have to move the scanner's position past the separator, as you have commented out in your code.

KerrM
  • 5,139
  • 3
  • 35
  • 60
  • Thank's for the great answer, but I wanted to stick with the scanner as I want to do some more filtering ... so +1 but I gave the close to the first time poster... – ICL1901 Aug 11 '14 at 18:28
1

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

jplego
  • 91
  • 4
  • Thanks a ton, and welcome to SO. Great answer and much appreciated. I was hoping that the world would change the spelling of seperator, but I guess it's not to be.... – ICL1901 Aug 11 '14 at 18:24