//
// WordManger.h
// OC7_单词个数
//
// Created by zhangxueming on 15/6/17.
// Copyright (c) 2015年 zhangxueming. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface WordManger : NSObject
{
NSMutableDictionary *
_wordList;
}
- (
id)initWithFile:(NSString *
)path;
- (
void)parseWordFile:(NSString *
)path;
- (NSInteger)firstWordCountInArray:(NSString *)word withArray:(NSMutableArray *
)mulArray;
+ (
void)userInterface;
@end
//
// WordManger.m
// OC7_单词个数
//
// Created by zhangxueming on 15/6/17.
// Copyright (c) 2015年 zhangxueming. All rights reserved.
//
#import "WordManger.h"
@implementation WordManger
- (
id)initWithFile:(NSString *
)path
{
self =
[super init];
if (self) {
_wordList =
[NSMutableDictionary dictionary];
[self parseWordFile:path];
}
return self;
}
- (
void)parseWordFile:(NSString *
)path
{
//读取单词文件
NSString *fileContent =
[NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
if (!
fileContent) {
return;
}
//分割字符串
NSArray *words = [fileContent componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:
@",. \n"]];
NSMutableArray *mulWords =
[NSMutableArray array];
for (NSString *item
in words) {
if (![item isEqualToString:
@""]) {
[mulWords addObject:[item lowercaseString]];
}
}
//统计单词出现的次数, 并添加到字典中
while ([mulWords count]) {
NSString *key = [mulWords objectAtIndex:
0];
NSNumber *value =
[NSNumber numberWithInteger:[self firstWordCountInArray:key withArray:mulWords]];
[_wordList setObject:value forKey:key];
[mulWords removeObject:key];
}
}
- (NSInteger)firstWordCountInArray:(NSString *)word withArray:(NSMutableArray *
)mulArray
{
NSInteger cnt =
0;
for (NSString *item
in mulArray) {
if ([item isEqualToString:word]) {
cnt++
;
}
}
return cnt;
}
+ (
void)userInterface
{
WordManger *manger = [[WordManger alloc] initWithFile:
@"/Users/zhangxueming/Downloads/qfile-10.txt"];
NSInteger cnt;
scanf("%li",&
cnt);
NSLog(@"keys = %@", [manger->
_wordList allKeysForObject:[NSNumber numberWithInteger:cnt]]);
}
@end
//
// main.m
// OC7_单词个数
//
// Created by zhangxueming on 15/6/17.
// Copyright (c) 2015年 zhangxueming. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "WordManger.h"
int main(
int argc,
const char *
argv[]) {
@autoreleasepool {
[WordManger userInterface];
}
return 0;
}
转载于:https://www.cnblogs.com/0515offer/p/4584168.html
相关资源:Java 单词长度 Mooc