如何在Objective C中从NSString中拆分换行符

时间:2012-04-29 07:41:08

标签: iphone objective-c ios xcode nsstring

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

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”,+ 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++){      
    //
}

1 个答案:

答案 0 :(得分:13)

可能希望了解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有一个适当的库来满足这种需求:https://github.com/davedelong/CHCSVParser