//
// main.m
// OC06_省市区
//
// Created by lanou3g on 17/8/2.
// Copyright © 2017年 lanou3g. All rights reserved.
//
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
//创建省份数组
NSMutableArray *provinceArray = [NSMutableArray array];
//加载文件得到的字符串
//参数1:文件路径
//参数2:编码格式
//参数3:错误信息
// NSError *error = nil;
NSString *contentString = [NSString stringWithContentsOfFile:@"/Users/lanou3g/Downloads/area.txt" encoding:NSUTF8StringEncoding error:nil];
// NSLog(@"%@",contentString);
//用\n分割字符串,得到每一行的字符串内容
NSArray *lineArray = [contentString componentsSeparatedByString:@"\n"];
for (NSString *lineString in lineArray) {
// NSLog(@"line:%@",lineString);
if (![lineString hasPrefix:@" "]) {
//前缀不是空格的话为省名
//创建一个省份字典
NSMutableDictionary *provienceDic = [NSMutableDictionary dictionary];
//省份字典添加键值对(provienceName:省份名)
[provienceDic setObject:lineString forKey:@"provienceName"];
//创建一个城市数组(ps:用于后面存储城市字典)
NSMutableArray *cityArray = [NSMutableArray array];
//添加键值对(cityArray:城市数组)
[provienceDic setObject:cityArray forKey:@"cityArray"];
//将省份字典添加到省份数组中
[provinceArray addObject:provienceDic];
}else if(![lineString hasPrefix:@" "]) {
//前缀有空格且不是4个空格的话为城市名
//当读取到城市名的时候需要找到该城市所属的省份(ps:当前省份数组中最后一个元素就是当前城市所属省份)
NSMutableDictionary *provienceDic = [provinceArray lastObject];
NSMutableArray *cityArray = [provienceDic 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 *areArray = [cityDic objectForKey:@"areaArray"];
//将地区名存入该地区数组
[areArray addObject:lineString];
}
}
// NSLog(@"%@",provinceArray);
//遍历
for (NSMutableDictionary *provinceDic in provinceArray) {
NSLog(@"省份:%@",[provinceDic objectForKey:@"provienceName"]);
for (NSMutableDictionary *cityDic in [provinceDic objectForKey:@"cityArray"]) {
NSLog(@"城市:%@",[cityDic objectForKey:@"cityName"]);
for (NSString *areaName in [cityDic objectForKey:@"areaArray"]) {
NSLog(@"地区:%@",areaName);
}
}
}
return 0;
}
网友评论