OC-电子词典

MyDictionary.h

#import <Foundation/Foundation.h>

#define PATH @"/Users/qianfeng/Desktop/dict.txt"

#define NSLOG(a) NSLog(@"%@",a); 

@interface MyDictionary : NSObject


-(NSString *)readfile;//对象函数:读取文本文件

-(NSMutableDictionary *)analysis;//对象函数:装载字典

-(NSString *)searchwith;//查找字典

+(void)interface;//类函数:测试字典

@end




MyDictionary.m

#import "MyDictionary.h"


@implementation MyDictionary


//读取文本内容,装入字符串,

-(NSString *)readfile{

    NSString *path = PATH;

    NSString *str = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];

    //    NSLOG(str);

    return str;

}


//把上一步得到的字符串转换为数组,然后装载字典

-(NSMutableDictionary *)analysis{

    //创建可变字典:

    NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];

    

    //获取文本内容:

    NSString *str =  [self readfile];

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

    NSInteger lenth = [array count];

    dictionary = [[NSMutableDictionary alloc] init];

    //装载字典:

    for (NSInteger i = 0;i<lenth-1;i+=2) {

        NSString *key = [array objectAtIndex:i];

        NSString *value = [array objectAtIndex:i+1];

        key = [key substringFromIndex:1];

        value = [value substringFromIndex:6];

        value = [value stringByReplacingOccurrencesOfString:@"@" withString:@"\n"];

        [dictionary setObject:value forKey:key];

    }

    return dictionary;

}


//查找字典:

-(NSString *)searchwith{

    //从函数“analysis”获取装载后的字典:

    

    NSMutableDictionary *dictionary = [self analysis];

    NSLOG(@"输入单词:\n");

    char buff[100];

    scanf("%s",buff);

    NSString *word = [NSString stringWithFormat:@"%s",buff];

    //返回结果:

    NSString *resultword =[dictionary objectForKey:word];

    return resultword;

}


//用类函数打印结果:

+(void)interface{

    NSLOG([[[MyDictionary alloc] init] searchwith]);

}


@end




main.m

#import <Foundation/Foundation.h>

#import "MyDictionary.h"

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

{

    @autoreleasepool {

        

        // insert code here...

        NSLog(@"Hello, World!");

        

        [MyDictionary interface];

        

    }

    return 0;

}









评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值