0
votes

I am able to get the CSV file data into array, but when it is taking the data of next line, it is taking a \n character. how to remove the \n character.

My CSV FILE contents are:

Hello,World,hhh
nnn,sss,eee

I am getting the output as

2011-08-24 15:29:16.069 CSVParsing[1030:903] (
    Hello
)
2011-08-24 15:29:16.072 CSVParsing[1030:903] (
    World
)
2011-08-24 15:29:16.075 CSVParsing[1030:903] (
    "hhh\nnnn"
)
2011-08-24 15:29:16.076 CSVParsing[1030:903] (
    sss
)
2011-08-24 15:29:16.077 CSVParsing[1030:903] (
    "eee\n"
)

How to overcome this problem

Following is the code i am Using.

{
NSString *pathToFile =[[NSBundle mainBundle] pathForResource:@"hw" ofType: @"csv"]; NSError *error;

NSString *fileString = [NSString stringWithContentsOfFile:pathToFile encoding:NSUTF8StringEncoding error:&error];
if (!fileString) {
    NSLog(@"Error reading file.");
} 
scanner = [NSScanner scannerWithString:fileString];    
[scanner setCharactersToBeSkipped:[NSCharacterSet characterSetWithCharactersInString:@","]];


while ([scanner scanUpToString:@"," intoString:&pathToFile]  )
{
    arrayItems = [pathToFile componentsSeparatedByString:@","];


    NSLog(@"%@",arrayItems);

}

}

3

3 Answers

0
votes

You can use

NSMutableString * string = @"hhh\nnnn";

NSRange foundRange = [string rangeOfString:@"\n"];

if (foundRange.location != NSNotFound)
{  
    [string replaceCharactersInRange:foundRange withString:@""];
}
0
votes

One way to do it is this: separate your file into an array of lines first:

// lineArray is a NSArray
// filedata is a NSString containing the full file

self.lineArray = [filedata componentsSeparatedByString:@"\n"];
0
votes

You just scan over the end of the line, treating newline just as another character. You could fix this by wrapping your scanner code into enumerateLinesUsingBlock:, which is an NSString method.

But really, this is then not a complete parser. You might have to handle a lot of special cases. Maybe you should look around, there is for example this one:

Where can I find a CSV to NSArray parser for Objective-C?