当字符串包含\ n时,NSScanner失败

时间:2012-09-20 21:53:46

标签: objective-c ios nsstring

有人知道当\ n添加到字符串时NSScanner是否会正确扫描?

例如,我有一个要扫描的字符串(myString)“\ nTest \ nSuper \ n”

NSScanner *scanner = [NSScanner scannerWithString:myString];
NSString *str = @"Super";
if( [scanner scanString:str intoString:nil] )
{
    //It never reaches here
}

为什么它没有看到“超级”的任何想法?当我没有\ n符号时,这曾经工作。

由于

1 个答案:

答案 0 :(得分:1)

-[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中看到第一次和第三次扫描的所有换行符。

祝你工作顺利。

相关问题