gpt4 book ai didi

iphone - iOS 中的 CSV 逐行解析

转载 作者:行者123 更新时间:2023-12-03 20:27:35 26 4
gpt4 key购买 nike

我正在 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行(含)的内容。然后,我想将每一行分成两个 NSString,一个包含 , 之前的内容,另一个包含其之后的内容。我怎样才能做到这一点?

非常感谢任何帮助。谢谢!安托万

最佳答案

尝试使用 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];

然后您应该使用三种委托(delegate)方法的组合来自定义解析器并使其满足您的需求:

- (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.
}
}

关于iphone - iOS 中的 CSV 逐行解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14536832/

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