8

For my new project. i have loaded my csv file content as a NSString. First, i need to split this by newline, then split each line by comma. How can i loop all this? Could you please help me?

CSV Content

"^GSPC",1403.36,"4/27/2012","4:32pm",+3.38,1400.19,1406.64,1397.31,574422720 "^IXIC",3069.20,"4/27/2012","5:30pm",+18.59,3060.34,3076.44,3043.30,0

ViewController.m

NSString* pathToFile = [[NSBundle mainBundle] pathForResource: @"quotes" ofType: @"csv"];
NSString *fileString = [NSString stringWithContentsOfFile:pathToFile encoding:NSUTF8StringEncoding error:nil];
if (!fileString) {
    NSLog(@"Error reading file.");
}

NSArray *array = [fileString componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];

for(int i=0; i<[array count]; i++){      
    //
}
shebi
  • 707
  • 2
  • 14
  • 23
  • See [this question](http://stackoverflow.com/questions/32021712/how-to-split-a-string-by-new-lines-in-swift) for Swift answers – Suragch Aug 18 '15 at 03:38

1 Answers1

13

Might want to look into NSMutableArray.

// grab your file
NSMutableArray *data = [[fileString componentsSeparatedByCharactersInSet: [NSCharacterSet newlineCharacterSet]] mutableCopy];
for (int i = 0; i < [data count]; i++)
{
    [data replaceObjectAtIndex: i
                    withObject: [[data objectAtIndex: i] componentsSeparatedByString: @","]];
}

Relatedly, Dave DeLong has a proper library to address this need: https://github.com/davedelong/CHCSVParser

Patrick Perini
  • 22,555
  • 12
  • 59
  • 88
  • Thank you pcperini. But, when i set this [data count] to my table numberOfRowsInSection, it is 5, not 2. please help me – shebi Apr 29 '12 at 08:14
  • @shebi check your text (csv) file within a Hex-Editor and see if it uses \r\n instead of \n. – Till Apr 29 '12 at 09:01