这与lead_the_zeppelin's answer 的一般程序相同,但我认为它要简单得多。我们使用NSMutableString、accum 来构建每个内部评论片段,其中可能包含任意数量的引用片段。
每次迭代,我们都会扫描到逗号、引号或字符串的结尾,以先到者为准。如果我们找到一个逗号,那么到目前为止积累的任何东西都应该被保存。对于引用,我们将所有内容提取到右引号 - 这是避免将引号内的逗号解释为分割点的关键。请注意,如果引号并不总是平衡的,这将不起作用。如果两者都不是,我们已经到了字符串的末尾,所以我们保存累积的字符串并退出。
// Demo data
NSArray * commaStrings = @[@"This, here, \"has\" no quoted, commas.",
@"This \"has, no\" unquoted \"commas,\"",
@"This, has,no,quotes",
@"This has no commas",
@"This has, \"a quoted\" \"phrase, followed\", by a, quoted phrase",
@"\"This\", one, \"went,\", to, \"mar,ket\"",
@"This has neither commas nor quotes",
@"This ends with a comma,"];
NSCharacterSet * commaQuoteSet = [NSCharacterSet characterSetWithCharactersInString:@",\""];
for( NSString * commaString in commaStrings ){
NSScanner * scanner = [NSScanner scannerWithString:commaString];
// Scanner ignores whitespace by default; turn that off.
[scanner setCharactersToBeSkipped:nil];
NSMutableArray * splitStrings = [NSMutableArray new];
NSMutableString * accum = [NSMutableString new];
while( YES ){
// Set to an empty string for the case where the scanner is
// at the end of the string and won't scan anything;
// appendString: will die if its argument is nil.
NSString * currScan = @"";
// Scan up to a comma or a quote; this will go all the way to
// the end of the string if neither of those exists.
[scanner scanUpToCharactersFromSet:commaQuoteSet
intoString:&currScan];
// Add the just-scanned material to whatever we've already got.
[accum appendString:currScan];
if( [scanner scanString:@"," intoString:NULL] ){
// If it's a comma, save the accumulated string,
[splitStrings addObject:accum];
// clear it out,
accum = [NSMutableString new];
// and keep scanning.
continue;
}
else if( [scanner scanString:@"\"" intoString:NULL] ) {
// If a quote, append the quoted segment to the accumulation,
[scanner scanUpToString:@"\""
intoString:&currScan];
[accum appendFormat:@"\"%@\"", currScan];
// and continue, appending until the next comma.
[scanner scanString:@"\"" intoString:NULL];
continue;
}
else {
//Otherwise, there's nothing else to split;
// just save the remainder of the string
[splitStrings addObject:accum];
break;
}
}
NSLog(@"%@", splitStrings);
}
另外,as Chuck suggested,您可能只想获得一个 CSV 解析器。