我有一个包含四个字段的CSV文件,“Woonplaats”,“Gemeente”,“Provincie”,“Latitude”和“Longitude”。
示例值:
Graveland,Wijdemeren,Noord-Holland,52.24412000,5.12150000
使用下面的代码,我在文本中获取字符串,然后我想将其保存在数组中。我应该如何使用NSScanner
从此字符串中获取数据并保存在包含字典的数组中?
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"cities" ofType:@"csv"];
NSString *myText = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil ];
NSScanner *scanner = [NSScanner scannerWithString:myText];
[scanner setCharactersToBeSkipped:[NSCharacterSet characterSetWithCharactersInString:@"\n ,"]];
NSMutableArray *newPoints = [NSMutableArray array];
答案 0 :(得分:1)
我相信这就是你要找的东西。我使用Dan Wood论坛帖子并根据您的需要对其进行了修改。
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
// insert code here...
NSString *path =@"cities.csv";
NSError *error;
NSString *stringFromFileAtPath = [[NSString alloc]
initWithContentsOfFile:path
encoding:NSUTF8StringEncoding
error:&error];
NSMutableDictionary *lineDict = [NSMutableDictionary dictionary];
NSArray *lines = [stringFromFileAtPath componentsSeparatedByString:@"\n"];
NSEnumerator*theEnum = [lines objectEnumerator];
NSArray *keys = nil;
int keyCount = 0;
NSString *theLine;
while (nil != (theLine = [theEnum nextObject]) )
{
if (![theLine isEqualToString:@""] && ![theLine hasPrefix:@"#"]) // ignore empty lines and lines that start with #
{
if (nil == keys) // Is keys not set yet? If so, process first real line as list of keys
{
keys = [theLine componentsSeparatedByString:@","];
keyCount = [keys count];
}
else // A data line
{
NSArray *values = [theLine componentsSeparatedByString:@","];
int valueCount = [values count];
int i;
for ( i = 0 ; i < keyCount && i < valueCount ; i++ )
{
NSString *value = [values objectAtIndex:i];
if (nil != value && ![value isEqualToString:@""])
{
[lineDict setObject:value forKey:[keys objectAtIndex:i]];
}
}
}
}
}
for (id key in lineDict)
{
NSLog(@"key: %@, value: %@", key, [lineDict objectForKey:key]);
}
[pool drain];
return 0;
}
输出是:
2011-07-13 20:02:41.898 cities[5964:903] key: Latitude, value: 52.24412000
2011-07-13 20:02:41.900 cities[5964:903] key: Provincie, value: Noord-Holland
2011-07-13 20:02:41.900 cities[5964:903] key: Longitude, value: 5.12150000
2011-07-13 20:02:41.901 cities[5964:903] key: Gemeente, value: Wijdemeren
2011-07-13 20:02:41.902 cities[5964:903] key: Woonplaats, value: Graveland