gpt4 book ai didi

objective-c - NSScanner - 将下一行扫描到字符串中

转载 作者:行者123 更新时间:2023-12-03 17:00:44 29 4
gpt4 key购买 nike

我正在使用 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];

所以数据的格式如下:整数,整数字符串字符串字符串

有时,第二个字符串(about)为空,NSScanner 会跳过它并将 gameBoard 字符串读取到 about 中。如何告诉 NSScanner 读取下一行?

最佳答案

解决方案 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"];

然后循环遍历并单独解析这些行。

关于objective-c - NSScanner - 将下一行扫描到字符串中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1022884/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com