开发者

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

开发者 https://www.devze.com 2023-03-30 14:52 出处:网络
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.

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);

}

}


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?


You can use

NSMutableString * string = @"hhh\nnnn";

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

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


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

精彩评论

暂无评论...
验证码 换一张
取 消