有谁知道当字符串中添加\n 时 NSScanner 是否会正确扫描?
例如,我有一个要扫描的字符串(myString)“\nTest\nSuper\n”
NSScanner *scanner = [NSScanner scannerWithString:myString];
NSString *str = @"Super";
if( [scanner scanString:str intoString:nil] )
{
//It never reaches here
}
有什么想法为什么看不到“ super ”吗?当我没有\n 符号时,这曾经有效。
谢谢
最佳答案
-[NSScanner scanString:intoString:]
返回 NO
因为您尝试从字符串的开头进行扫描,而子字符串“Super”则不会发生在那里。
我将用它来尝试说明发生的情况:
BOOL success;
NSString *whatDidIGet;
// 'success' is YES, and 'whatDidIGet' contains "Test\n"
whatDidIGet = nil;
success = [scanner scanUpToString:str intoString:&whatDidIGet];
// 'success' is YES, and 'whatDidIGet' contains "Super"
whatDidIGet = nil;
success = [scanner scanString:str intoString:&whatDidIGet];
// 'success' is NO, and 'whatDidIGet' is nil.
whatDidIGet = nil;
success = [scanner scanUpToString:str intoString:&whatDidIGet];
第一个换行符被忽略的原因是您的扫描仪(您设置它的方式)默认情况下会忽略空格和换行符,因此它会跳过第一个。最后,再次,因为它跳过空格和换行符,所以 whatDidIGet
为零。
编辑:
如果您在实例化扫描仪后立即插入此内容:
[scanner setCharactersToBeSkipped:[[[NSCharacterSet alloc] init] autorelease]];
您会在第一次和第三次扫描的 whatDidIGet
中看到所有换行符。
祝您工作顺利。
关于objective-c - 当字符串包含时 NSScanner 失败\n,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12521478/