2011-06-24 42 views
1

我需要拆分一个由逗号分隔的字符串,同时保留任何带引号的子字符串(也可能带有逗号)。拆分NSString保留带引号的子字符串

字符串例如:

NSString *str = @"One,Two,\"This is part three, I think\",Four"; 
for (id item in [str componentsSeparatedByString:@","]) 
    NSLog(@"%@", item); 

这将返回:

  • 一个
  • 两个
  • “这是三部分
  • 我觉得”

正确的结果(尊重引述子)应为:

  • 一个
  • 两个
  • “这是第三部分,我认为”

有一个合理的方式来做到这一点,而不需要重新发明或重写引用感知解析例程?

+0

正则表达式http://developer.apple.com/library/ios/#documentation /Foundation/Reference/NSRegularExpression_Class/Reference/Reference.html – Joe

回答

2

让我们来想想这样一种不同的方式。你有什么是一个逗号分隔的字符串,你想要字符串中的字段。

有针对一些代码:

https://github.com/davedelong/CHCSVParser

而且你应该这样做:

NSString *str = @"One,Two,\"This is part three, I think\",Four"; 
NSArray *lines = [str CSVComponents]; 
for (NSArray *line in lines) { 
    for (NSString *field in line) { 
    NSLog(@"field: %@", field); 
    } 
} 
相关问题