本文介绍了如何在ObjectiveC中从NSString中拆分换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我的新项目。我已将我的csv文件内容加载为NSString。
首先,我需要通过换行拆分它,然后用逗号分隔每一行。
如何循环所有这些?你能帮我吗?

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内容

^ GSPC, 1403.36,4/27/2012,4:32 pm,+ 3.38,1400.19,1406.64,1397.31,574422720^ IXIC,3069.20,4/27/2012,5:30 pm,+ 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/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++){      
    //
}


推荐答案

可能要查看 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: @","]];
}

相关地,Dave DeLong有一个合适的库来满足这个需求:

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

这篇关于如何在ObjectiveC中从NSString中拆分换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 02:07