为什么我的数组中的所有其他对象都是空白的?
我使用以下方法将 CSV 文件读入数组:
NSString *theWholeTable = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"example" ofType:@"csv"]
encoding:NSUTF8StringEncoding
error:NULL];
NSArray *tableRows = [theWholeTable componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
数组中的每个第二个对象都是空的,知道为什么吗?
CSV 文件数据如下所示: 10,156,326,614,1261,1890,3639,5800,10253,20914 20,107,224,422,867,1299,2501,3986,7047,14374
,其中 10 和 20 是每行新行的开头。
提前致谢。
编辑 我尝试使用以下代码:
NSArray *tableRows = [theWholeTable componentsSeparatedByString:@"\n"];
这也按照我想要的方式工作。
虽然我仍然不确定为什么 newlineCharacterSet 创建空对象......
I read a CSV file into an array using:
NSString *theWholeTable = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"example" ofType:@"csv"]
encoding:NSUTF8StringEncoding
error:NULL];
NSArray *tableRows = [theWholeTable componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
And every second object in the array is empty, any idea why?
the CSV file data looks like this:
10,156,326,614,1261,1890,3639,5800,10253,20914
20,107,224,422,867,1299,2501,3986,7047,14374
with 10 and 20 being the start of each new line.
thanks in advance.
Edit
I tried using the following code instead:
NSArray *tableRows = [theWholeTable componentsSeparatedByString:@"\n"];
And that worked the way I wanted it too.
Although I am still unsure why the newlineCharacterSet created empty objects...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您的
CSV
文件来自非 UNIX 系统,它可能包含多个行分隔符(例如\r\n
而不是\n
) 。在这种情况下,componentsSeparatedByCharactersInSet
将在\r
和\n
之间插入空字符序列的空字符串。您可以使用以下方法从
NSArray
中删除空字符串:If your
CSV
file comes from a non-UNIX system, it may contain multiple line separators (e.g.\r\n
instead of\n
). In this case,componentsSeparatedByCharactersInSet
will insert empty strings for empty character sequences between\r
and\n
.You can remove empty strings from
NSArray
using this method:为了解决这个问题,我使用了其他方法:
所以你不需要删除任何行。
to solve this problem, I have used other way:
So you wouldn't need remove any lines.