码迷,mamicode.com
首页 > 其他好文 > 详细

OC4_电子词典

时间:2015-06-15 20:14:50      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:

//
//  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;
}

 

OC4_电子词典

标签:

原文地址:http://www.cnblogs.com/0515offer/p/4578838.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!