NSScanner中的额外字符(objective-C)

时间:2014-08-11 16:19:15

标签: objective-c nsscanner

我在NSScanner中解析字符串时遇到了一个小问题。我已经阅读了其他SO帖子,但无法解决这个愚蠢的问题。

我有一个像这样的字符串“第一个字不是=第二个字”

我的代码是:

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

问题是我将分隔符作为secondString的一部分。

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

2 个答案:

答案 0 :(得分:1)

所以你想分开字符串?您可以使用NSString的componentsSeparatedByString方法。

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

如果您想使用扫描仪,您必须将扫描仪的位置移动到分隔符之外,就像您在代码中注释掉一样。

答案 1 :(得分:1)

这是我在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);

得到了:

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

为了后人检查'分隔符'拼写