关闭

objective-c 算法积累

标签: iOSobjective-c字符串中单词个数
358人阅读 评论(0) 收藏 举报
分类:

1.获取字符串中单词的计数?

- (NSInteger)countWord:(NSString *)string{

    NSMutableArray *ary = [NSMutableArray arrayWithCapacity:0];

    NSString *danci = @"";

    for (NSInteger i = 0; i < string.length; i++) {

        NSString *ch = [NSString stringWithFormat:@"%@",[string substringWithRange:NSMakeRange(i, 1)]];

        if (([ch characterAtIndex:0] >= [@"A" characterAtIndex:0] && [ch characterAtIndex:0] <= [@"Z" characterAtIndex:0]) || ([ch characterAtIndex:0] >= [@"a" characterAtIndex:0] && [ch characterAtIndex:0] <= [@"z" characterAtIndex:0])) {

            danci = [danci stringByAppendingString:ch];

        }else {

            if (danci.length > 0) {

                [ary addObject:danci];

                danci = @"";

            }

        }

    }

    return ary.count;

}

2.统计字符串中每个单词的出现的计数?

- (NSDictionary *)dicCountWord:(NSString *)string{

    NSMutableArray *ary = [NSMutableArray arrayWithCapacity:0];

    NSString *danci = @"";

    for (NSInteger i = 0; i < string.length; i++) {

        NSString *ch = [NSString stringWithFormat:@"%@",[string substringWithRange:NSMakeRange(i, 1)]];

        if (([ch characterAtIndex:0] >= [@"A" characterAtIndex:0] && [ch characterAtIndex:0] <= [@"Z" characterAtIndex:0]) || ([ch characterAtIndex:0] >= [@"a" characterAtIndex:0] && [ch characterAtIndex:0] <= [@"z" characterAtIndex:0])) {

            danci = [danci stringByAppendingString:ch];

        }else {

            if (danci.length > 0) {

                [ary addObject:danci];

                danci = @"";

            }

        }

    }

    

    NSMutableDictionary *wordDic = [NSMutableDictionary dictionaryWithCapacity:0];

    NSString *newStr = @"";

    NSInteger count = 0;

    for (int j = 0; j < ary.count; j++) {

        for (int i = 0; i < ary.count; i++) {

            if ((newStr.length < 1) && (![ary[i] isEqualToString:@""])) {

                newStr = [NSString stringWithFormat:@"%@",ary[i]];

                count = 1;

                [ary replaceObjectAtIndex:i withObject:@""];

            }else {

                if ((newStr.length > 0) && ([ary[i] isEqualToString:newStr])) {

                    newStr = [NSString stringWithFormat:@"%@",ary[i]];

                    count++;

                    [ary replaceObjectAtIndex:i withObject:@""];

                }

            }

            if (i == ary.count-1) {

                if (count != 0 && ![newStr isEqualToString:@""]) {

                    [wordDic setObject:@(count) forKey:newStr];

                }

                newStr = @"";

                count = 0;

            }

        }

    }

    return wordDic;

}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:479897次
    • 积分:5933
    • 等级:
    • 排名:第4254名
    • 原创:61篇
    • 转载:254篇
    • 译文:17篇
    • 评论:12条
    文章分类
    最新评论