您的位置:首页 > 其它

OC NSDictionary 省市区 练习

2015-08-12 14:42 225 查看
#import <Foundation/Foundation.h>

int main(int argc, const char *
argv[]) {



NSString *string = [[NSString alloc] initWithContentsOfFile:@"/Users/dllo/Downloads/area.txt"encoding:NSUTF8StringEncoding error:nil];

//NSLog(@"%@", string);

// 以 @"\n" 分割字符串 放入数组

NSArray *array = [string componentsSeparatedByString:@"\n"];

//NSLog(@"%@", array);

//遍历数组

//省数组

NSMutableArray *province = [NSMutableArray arrayWithCapacity:0];

//市数组

NSMutableArray *citys = [NSMutableArray array];

//区域数组

NSMutableArray *areas = [NSMutableArray array];

//省字典

NSMutableDictionary *pro;

//市字典

NSMutableDictionary *city;
for (NSString *string in array) {

/***********************************

判断逻辑:当前面有四个空格的时候为区(if)

当前面有两个空格的时候为市(else if)

其余情况为省(else)

**********************************/
if ([string hasPrefix:@" "]) {

//判断是否为最后一个元素
if ([array indexOfObject:string] == (array.count - 1))
{
//判断省字典是否存在
if (pro) {
//将数组保存至字典
[pro setObject:citys forKey:@"city"];
}
//判断市字典是否存在
if (city) {
[city setObject:areas forKey:@"area"];
}
}

//截取区域字符串的前面的两个空格
NSString *otherString = [string substringFromIndex:4];
//分割 字符串
NSArray *array = [otherString componentsSeparatedByString:@"
"];
//定义区字典

NSMutableDictionary *area = [NSMutableDictionarydictionaryWithObjectsAndKeys:[array objectAtIndex:0],[array objectAtIndex:1], nil];
//将区字典添加到区数组
[areas addObject:area];


} else if ([string hasPrefix:@"
"]) {
if (city) {
//将区字典加入市字典
[city setObject:areas forKey:@"area"];
//初始化区数组
areas = [NSMutableArray array];
}

//截取掉市字符串前面两个空格
NSString *otherString = [string substringFromIndex:2];
//把市字符串和编号分开
NSArray *array = [otherString componentsSeparatedByString:@"
"];
//初始化市字典

city = [NSMutableDictionary dictionaryWithObjectsAndKeys:[array objectAtIndex:0],
[array objectAtIndex:1], nil];
//将市字典填入市数组
[citys addObject:city];

} else {
//判断省字典是否存在
if (pro) {
//将数组保存至字典
[pro setObject:citys forKey:@"city"];
//重新给城市空间数组
citys = [NSMutableArray array];
}
//把省和编号分开
NSArray *array = [string componentsSeparatedByString:@"
"];
pro = [NSMutableDictionary dictionary];//初始化省字典

[pro setObject:[array objectAtIndex:0] forKey:[array objectAtIndex:1]];
//将省字典加入省数组
[province addObject:pro];
}
}
NSLog(@"%@", province);


return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: