文本数据见博客中的《数组和字典的应用数据》
int main(int argc, const char * argv[])
{
//文件路径 可以把磁盘上的文件直接拖入项目即可得到文件路径
NSString *filePath = @"/Users/.../area.txt";
//错误信息
NSError *error = nil;
//把文件从磁盘读入内存 保存为字符串对象
NSString * buffer = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
//打印错误信息
if (error) {
NSLog(@"error : %@", [error localizedDescription]);
exit(1);
}
//以'\n'为分割符把字符串分割成数组
NSArray *array = [buffer componentsSeparatedByString:@"\n"];
NSCharacterSet *charSet = [NSCharacterSet characterSetWithCharactersInString:@" 0123456789"];
//创建一个可变数组做为数据封装的载体
NSMutableArray *provinces = [NSMutableArray array];
for (NSString *s in array) {
//找到一个省的名字(省名左对齐)
if (![s hasPrefix:@" "]) {
//创建用于保存城市信息的数组
NSMutableArray *cities = [NSMutableArray array];
//把省名称的两边的空格和数字去掉
NSString *provinceName = [s stringByTrimmingCharactersInSet:charSet];
//把省名称和城市数组封装成字典
NSDictionary *pDic = [NSDictionary dictionaryWithObjectsAndKeys:provinceName,@"name",cities,@"cities", nil];
//添加到大数组中
[provinces addObject:pDic];
}
//找到一个城市的名字(城市名前只有两个空格)
if ([s hasPrefix:@" "] && ![s hasPrefix:@" "]) {
//获取最后一个添加的省信息的字典
NSDictionary *pDic = [provinces lastObject];
//获取最后一个添加的省的信息的字典中的城市数组
NSMutableArray *cities = [pDic objectForKey:@"cities"];
//把城市的名称的前后空格和数字去掉
NSString *cityName = [s stringByTrimmingCharactersInSet:charSet];
//创建保存区信息的数组
NSMutableArray *areas = [NSMutableArray array];
//把城市名称和区数组封装成字典
NSDictionary *cDic = [NSDictionary dictionaryWithObjectsAndKeys:cityName, @"name", areas, @"areas", nil];
//添加到对应的城市数组中
[cities addObject:cDic];
}
//找到一个区的名字(区名前有四个空格)
if ([s hasPrefix:@" "]) {
//获取最后一个添加的省信息的字典
NSDictionary *pDic = [provinces lastObject];
//获取最后一个添加的省的信息的字典中的城市数组
NSMutableArray *cities = [pDic objectForKey:@"cities"];
//获取城市数组中最后一个添加的城市字典
NSDictionary *cDic = [cities lastObject];
//获取城市字典中的区数组
NSMutableArray *areas = [cDic objectForKey:@"areas"];
//把区的名称的前后空格和数字去掉
NSString *areaName = [s stringByTrimmingCharactersInSet:charSet];
//添加到对应区数组口
[areas addObject:areaName];
}
}
NSLog(@"%@", provinces);
//查找并输出山东省威海市的所有区的名称(测试)
for (NSDictionary *dic in provinces) {
NSString *pName = [dic objectForKey:@"name"];
if ([pName hasPrefix:@"山东"]) {
NSArray *cities = [dic objectForKey:@"cities"];
for (NSDictionary *cDic in cities) {
NSString *cName = [cDic objectForKey:@"name"];
if ([cName hasPrefix:@"威海"]) {
NSArray *areas = [cDic objectForKey:@"areas"];
for (NSString *s in areas) {
NSLog(@"%@",s);
}
}
}
}
}
return 0;
}