NSScanner vs.componentsSeparatedByString [英] NSScanner vs. componentsSeparatedByString
问题描述
我有一个大文本文件(大约10 MB).在文本文件中,有一些类似的值(行之间没有空行,我在这里无法正确设置其格式):
I have a large text file (about 10 MB). In the text file there are values like (without the empty lines between the rows, I couldn't format it here properly):
;string1;stringValue1;
;string2;stringValue2;
;string3;stringValue3;
;string4;stringValue4;
我正在使用一个非常丑陋的解决方案将所有'stringX'值解析为一个数组,并将'stringValueX'解析为另一个字符串:
I'm parsing all the 'stringX' values to an Array and the 'stringValueX' to another string, using a pretty ugly solution:
words = [rawText componentsSeparatedByString:@";"];
NSEnumerator *word = [words objectEnumerator];
while(tmpWord = [word nextObject]) {
if ([tmpWord isEqualToString: @""] || [tmpWord isEqualToString: @"\r\n"] || [tmpWord isEqualToString: @"\n"]) {
// NSLog(@"%@*** NOTHING *** ",tmpWord);
}else { // here I add tmpWord the arrays...
I've tried to do this using NSScanner
by following this example: http://www.macresearch.org/cocoa-scientists-part-xxvi-parsing-csv-data
但是我收到了内存警告,然后全部崩溃了.
But I received memory warnings and then it all crashed.
我可以使用 NSScanner
进行此操作吗?如果可以,那么任何人都可以给我一个如何执行此操作的示例吗?
Shall I do this using NSScanner
and if so, can anyone give me an example of how to do that?
谢谢!
推荐答案
在大多数情况下, NSScanner
比 componentsSeparatedByString:
更适合,尤其是在尝试保留内存的情况下
In most cases NSScanner
is better suited than componentsSeparatedByString:
, especially if you are trying to preserve memory.
您的文件可以通过这样的循环进行解析:
Your file could be parsed by a loop like this:
while (![scanner isAtEnd]) {
NSString *firstPart = @"";
NSString *secondPart = @"";
[scanner scanString: @";" intoString: NULL];
[scanner scanUpToString: @";" intoString: &firstPart];
[scanner scanString: @";" intoString: NULL];
[scanner scanUpToString: @";" intoString: &secondPart];
[scanner scanString: @";" intoString: NULL];
// TODO: add firstPart and secondPart to your arrays
}
您可能需要为此添加错误检查代码,以防文件无效.
You probably need to add error-checking code to this in case you get an invalid file.
这篇关于NSScanner vs.componentsSeparatedByString的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!