//
// MyDictionary.h
// OC4_电子词典
//
// Created by zhangxueming on 15/6/15.
// Copyright (c) 2015年 zhangxueming. All rights reserved.
//
#import <Foundation/Foundation.h>
#define FilePath @"/Users/zhangxueming/Desktop/ios1509/Day16_类的复合设计/dict.txt"
@interface MyDictionary : NSObject
{
NSMutableDictionary *
_mulDict;
}
- (
id)initWithFile:(NSString *
)path;
+ (
void)userInterface;
@end
//
// MyDictionary.m
// OC4_电子词典
//
// Created by zhangxueming on 15/6/15.
// Copyright (c) 2015年 zhangxueming. All rights reserved.
//
#import "MyDictionary.h"
@interface MyDictionary ()
- (BOOL)parseFileContent:(NSString *
)path;
@end
@implementation MyDictionary
- (
id)initWithFile:(NSString *
)path
{
self =
[super init];
if (self) {
_mulDict =
[NSMutableDictionary dictionary];
[self parseFileContent:path];
}
return self;
}
- (BOOL)parseFileContent:(NSString *
)path
{
//读取字典文件
NSString *fileContent =
[NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
//判断是否读取成功
if(!
fileContent)
{
return NO;
}
//解析
NSArray *contentItems = [fileContent componentsSeparatedByString:
@"\n"];
NSInteger len =
[contentItems count];
for (NSInteger i=
0; i<len; i+=
2) {
if ([[contentItems objectAtIndex:i] isEqualToString:
@""]) {
continue;
}
NSString *key = [[contentItems objectAtIndex:i] substringFromIndex:
1];
NSString *value = [[[contentItems objectAtIndex:i+
1] substringFromIndex:
6] stringByReplacingOccurrencesOfString:
@"@" withString:
@"\n"];
[_mulDict setObject:value forKey:key];
}
return YES;
}
+ (
void)userInterface
{
MyDictionary *dict =
[[MyDictionary alloc] initWithFile:FilePath];
NSLog(@"欢迎使用电子词典");
char str[
50]=
{};
while (YES) {
NSLog(@"请输入要查找的单词:");
scanf("%s", str);
NSLog(@"翻译:%@",[dict->
_mulDict objectForKey:[NSString stringWithUTF8String:str]]);
}
}
@end
//
// main.m
// OC4_电子词典
//
// Created by zhangxueming on 15/6/15.
// Copyright (c) 2015年 zhangxueming. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "MyDictionary.h"
int main(
int argc,
const char *
argv[]) {
@autoreleasepool {
[MyDictionary userInterface];
}
return 0;
}
转载于:https://www.cnblogs.com/0515offer/p/4578838.html