我有格式附带的csv:
a1,a2,a3,“a4,a5”,a6
只有字段,会有引号
使用Objective-C,如何轻松解析这个?我尽量避免使用开源CSV解析器作为公司策略。感谢。
答案 0 :(得分:1)
我同意rmaddy一个完整的csv解析算法超出了SO的范围,但是,这是解决这个问题的一种可能方法:
NSString
NSString
,将每个角色推回另一个字符串。这通常适用于任何语言(使用各自的本机字符串类),并且这种算法可以构成完整CSV解析器的小基础。但是,在这种特殊情况下,您可能不需要任何其他功能。
对于某些示例代码,我建议您查看my answer to this CSV-related question,因为它演示了在Objective-C中拆分和存储字符串的方法。
答案 1 :(得分:0)
此代码段非常适合我...
BOOL quotesOn = false;
NSString* line = @"a1, a2, a3, "a4,a5", a6";
NSMutableArray* lineParts = [[NSMutableArray alloc] init];
NSMutableString* linePart = [[NSMutableString alloc] init];
for (int i = 0; i < line.length; i++)
{
unichar current = [line characterAtIndex: i];
if (current == '"')
{
quotesOn = !quotesOn;
continue;
}
if (!quotesOn && current == ',')
{
if (linePart.length > 0)
[lineParts addObject: linePart];
linePart = [[NSMutableString alloc] init];
}
if (quotesOn || current != ',')
[linePart appendString: [line substringWithRange: NSMakeRange(i, 1)]];
}
if (linePart.length > 0)
[lineParts addObject: linePart];
我的5个元素在lineParts数组中...