我正在使用NSScanner来解析逗号和行分隔的数据。实现起来相当简单,但我遇到了一个非常简单的问题。我想扫描下一行,即使它是空的。我现在遇到的问题是,如果有一个空行,它将跳过它并读取下一行。然后我的解析关闭,因为错误的数据最终在错误的地方。这是我现在的代码:
NSCharacterSet *setToIgnore = [NSCharacterSet characterSetWithCharactersInString:@",\r\n"];
[scanner setCharactersToBeSkipped:setToIgnore];
NSInteger levelID, campaignID;
NSString *title, *about, *gameBoard;
BOOL aTest = [scanner scanInteger:&levelID] && [scanner scanInteger:&campaignID];
aTest = [scanner scanUpToString:@"\r\n" intoString:&title];
aTest = [scanner scanUpToString:@"\r\n" intoString:&about];
aTest = [scanner scanUpToString:@"\r\n" intoString:&gameBoard];
所以数据格式如下: INT,INT 串 串 串
有时,第二个字符串(about)为空,NSScanner会跳过它并将gameBoard字符串读入about。如何告诉NSScanner在下一行读取?
答案 0 :(得分:2)
解决方案1:删除setToIgnore
语句并手动扫描分隔符:
NSInteger levelID, campaignID;
NSString *title, *about, *gameBoard;
BOOL aTest = [scanner scanInteger:&levelID]
[scanner setScanLocation:[scanner scanLocation]+1]; // skip comma
aTest=[scanner scanInteger:&campaignID];
[scanner setScanLocation:[scanner scanLocation]+2]; // skip line break
aTest = [scanner scanUpToString:@"\r\n" intoString:&title];
[scanner setScanLocation:[scanner scanLocation]+2]; // skip line break
aTest = [scanner scanUpToString:@"\r\n" intoString:&about];
[scanner setScanLocation:[scanner scanLocation]+2]; // skip line break
aTest = [scanner scanUpToString:@"\r\n" intoString:&gameBoard];
[scanner setScanLocation:[scanner scanLocation]+2]; // skip line break
解决方案2:用以下内容替换整批:
NSArray *lines=[file componentsSeparatedByString:@"\r\n"];
然后循环并分别解析这些行。
答案 1 :(得分:1)
请勿忽略\r
和\n
。