在iOS中按行解析CSV [英] CSV parsing in iOS by line
问题描述
我解析目标c中的CSV文件。该文件包含如下内容:
I'm parsing a CSV file in objective-c. The file contains something like this:
line 40 | Rising searches
line 41 | nabi avcı,Breakout
line 42 | stonewall,+700%
line 43 | medgar evers,+500%
line 44 | lgbt,+350%
line 45 | roe v wade,+350%
line 46 | αÏεÏγια,+250%
我想获得41到50行)。然后我想把每一行分成两个 NSStrings
一个包含,
之前的东西,之后。我该如何做?
I want to get the contents of lines 41 to 50 (inclusive). I then want to separate the each line into two NSStrings
one containing the stuff before the ,
and the other with the stuff after it. How can I do that?
任何帮助真的非常感谢。谢谢! Antoine
Any help is really strongly appreciated. Thx! Antoine
推荐答案
尝试玩Dave DeLong的CHCSVParser。 https://github.com/davedelong/CHCSVParser
Try playing around with Dave DeLong's CHCSVParser. https://github.com/davedelong/CHCSVParser
您可以使用您的CSV文件的路径初始化解析器(假设您有一个CHCSVParser * _parser实例变量):
You can initialize the parser with the path to you CSV file (assuming you have a CHCSVParser *_parser instance variable):
NSString *filePath = ...; // the path to your CSV file
_parser = [[CHCSVParser alloc] initWithContentsOfCSVFile:filePath];
_parser.delegate = self;
[_parser parse];
然后,您应该使用三个委托方法的组合来自定义解析器,使其适合您的需要:
Then you should use a combination of three delegate methods to customize the parser and make it fit your needs:
- (void)parser:(CHCSVParser *)parser didBeginLine:(NSUInteger)recordNumber
{
// Only parse the fields on lines 41 to 50
// _shouldParseLine is an ivar that is set to YES
// only when the fields inside the following line or lines
// should be parsed.
if (recordNumber == 41) {
_shouldParseLine = YES;
}
}
- (void)parser:(CHCSVParser *)parser didEndLine:(NSUInteger)recordNumber
{
if (recordNumber == 50) {
// The parser has finished parsing the 50th line
// We're done, cancel any further parsing.
// It is not necessary to set _shouldParseLine to NO,
// since the parser is killed here and the didReadField
// delegate method will not be called again.
[parser cancelParsing];
}
}
- (void)parser:(CHCSVParser *)parser didReadField:(NSString *)field atIndex:(NSInteger)fieldIndex
{
if (_shouldParseLine == YES) {
// Here are your fields.
// The field at index 0 consists of the text
// before the comma, the field at index 1
// consists of the text after the comma.
}
}
这篇关于在iOS中按行解析CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!