xcode 如何在ObjectiveC中从NSString拆分换行符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10370516/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to split newline from NSString in ObjectiveC
提问by shebi
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 文件内容加载为 NSString。首先,我需要用换行符分割它,然后用逗号分割每一行。我怎么能循环这一切?请你帮助我好吗?
CSV Content
CSV 内容
"^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
"^GSPC",1403.36,"4/27/2012","4:32pm",+3.38,1400.19,1406.64,1397.31,574422720 "^IXIC",3069.20,"4/27/25:32pm" ",+18.59,3060.34,3076.44,3043.30,0
ViewController.m
视图控制器.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++){
//
}
回答by Patrick Perini
Might want to look into NSMutableArray
.
可能想看看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
相关地,Dave DeLong 有一个合适的库来满足这个需求:https: //github.com/davedelong/CHCSVParser