2

Objective-C で CSV ファイルを解析しています。ファイルには次のようなものが含まれています。

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次に、各行を、前のものと後のものを含む2つの行に分けたいと思い,ます。どうやってやるの?

どんな助けでも本当に高く評価されます。どうも!アントワーヌ

4

1 に答える 1

6

Dave DeLong の CHCSVParser をいじってみてください。https://github.com/davedelong/CHCSVParser

CSV ファイルへのパスを使用してパーサーを初期化できます (CHCSVParser *_parser インスタンス変数があると仮定します)。

NSString *filePath = ...; // the path to your CSV file
_parser = [[CHCSVParser alloc] initWithContentsOfCSVFile:filePath];
_parser.delegate = self;
[_parser parse];

次に、3 つのデリゲート メソッドの組み合わせを使用して、パーサーをカスタマイズし、ニーズに合わせます。

- (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.
    }
}
于 2013-01-26T12:54:02.093 に答える