Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it that every other object in my array is blank?

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

like image 231
Michael Campsall Avatar asked Dec 25 '11 04:12

Michael Campsall


2 Answers

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:

tableRows = [tableRows filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"length > 0"]];
like image 163
Sergey Kalinichenko Avatar answered Nov 03 '22 01:11

Sergey Kalinichenko


to solve this problem, I have used other way:

NSArray *tableRows = [theWholeTable componentsSeparatedByCharactersInSet:[NSCharacterSet  characterSetWithCharactersInString:@"\n"]]

So you wouldn't need remove any lines.

like image 25
xarly Avatar answered Nov 03 '22 00:11

xarly