#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
NSMutableArray *provinceArray = [NSMutableArray array];
//NSError *error =nil;
// 加载文件字符串 1.文件路径 2.编码格式3.错误信息
NSString *contentString = [NSString stringWithContentsOfFile:@"/Users/lanou3g/Desktop/area.txt" encoding:NSUTF8StringEncoding error:nil];
//NSLog(@"%@",contentString);
//以换行符分割字符串 得到每一行的字符串内容
NSArray *lineArray = [contentString componentsSeparatedByString:@"\n"];
for (NSString *lineString in lineArray) {
//NSLog(@"line:%@",lineString);
if (![lineString hasPrefix:@" "]) {
// 没有空格前缀为省名
//创建一个省份字典
NSMutableDictionary *provincrDic = [NSMutableDictionary dictionary];
// 省份字典添加键值对(provinceName省份名)
[provincrDic setObject:lineString forKey:@"provinceName"];
//创建一个城市数组(后面存储城市字典)
NSMutableArray *cityArray = [NSMutableArray array];
//添加键值对(cityArray:城市数组)
[provincrDic setObject:cityArray forKey:@"cityArray"];
//将省字典添加到省数组中
[provinceArray addObject:provincrDic];
}else if (![lineString hasPrefix:@" "]){
//前缀不空格且不是4个空格的话为城市名
//当读取到城市名的时候需要找到该城市所属的省份(省份数组中最后一个元素就是当前城市所属省份)
NSMutableDictionary *provinceDic =[provinceArray lastObject];
NSMutableArray *cityArray = [provinceDic objectForKey:@"cityArray"];
//创建城市字典
NSMutableDictionary *cityDic = [NSMutableDictionary dictionary];
//添加键值对(cityName城市名)
[cityDic setObject:lineString forKey:@"cityName"];
//创建地区数组(后面用于存储地区名称)
NSMutableArray *areaArray = [NSMutableArray array];
//添加键值对(areaArray:地区数组)
[cityDic setObject:areaArray forKey:@"areaArray"];
//将城市字典存入对应的城市数组中
[cityArray addObject:cityDic];
}else{
//前缀有空格且有4个空格为地区名
//获取当前所属省份
NSMutableDictionary *provinceDic = [provinceArray lastObject];
//获取该省份的城市数组
NSMutableArray *cityArray = [provinceDic objectForKey:@"cityArray"];
//从城市数组中获取当前地区所属城市
NSMutableDictionary *cityDic = [cityArray lastObject];
//获取该城市的地区数组
NSMutableArray *areaArray = [cityDic objectForKey:@"areaArray"];
//将地区名存入该地区数组
[areaArray addObject:lineString];
}
}
//NSLog(@"%@",provinceArray);
for (NSMutableDictionary *provinceDic in provinceArray) {
NSLog(@"省份:%@",[provinceDic objectForKey:@"provinceName"]);
for (NSMutableDictionary *cityDic in [provinceDic objectForKey:@"cityArray"]) {
NSLog(@"城市:%@",[cityDic objectForKey:@"cityName"]);
for (NSString *areaName in [cityDic objectForKey:@"areaArray"]) {
NSLog(@"地区:%@",areaName);
}
}
}
return 0;
}
这是在OC中利用数组和字典的相互套用解析的,附一张思维图。