码迷,mamicode.com
首页 > 编程语言 > 详细

oc将字符串中单词按照出现次数(次数都不一样)降序排序,排序之后单词只出现一次,源字符串中单词用下划线连接,生成字符串也用下滑线连接

时间:2015-06-19 10:21:52      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:

/*
 将字符串中单词按照出现次数(次数都不一样)降序排序,排序之后单词只出现一次,源字符串中单词用下划线连接,生成字符串也用下滑线连接(10分)
 如传入:@"good_good_study_good_study"
 返回:@"good_study"
 如传入:@"I_love_I_hate_love_love"
 返回:@"love_I_hate"
 */

方法1:选择排序

-(NSString *)sortStringByNumberOfWordsFromString:(NSString *)str
{
    NSArray *ary=[str componentsSeparatedByString:@"_"];
    NSMutableArray *difary=[[NSMutableArray alloc]init];
    [difary addObject:ary[0]];
    for (int i=0; i<ary.count; i++) {
        BOOL ret=NO;
        for (int m=0; m<difary.count; m++)
        {
            BOOL ifret=[ary[i]isEqualToString:difary[m]];
            if (ifret==YES) {ret=YES;break;}
        }
        if (ret==NO) {[difary addObject:ary[i]];}
    }
    NSLog(@"%@",difary);
    int num=0;
    int nun=0;
    for (int m=0; m<difary.count; m++) {
        for (int k=m; k<difary.count; k++) {
            for (int n=0; n<ary.count; n++) {
                if ([difary[m]isEqualToString:ary[n]]==YES) {
                    num++;
                }
                if ([difary[k]isEqualToString:ary[n]]==YES) {
                    nun++;
                }
            }
            if(num>nun)
            {
                NSString *temp=difary[m];
                difary[m]=difary[k];
                difary[k]=temp;
            }
            num=0;
            nun=0;
            NSLog(@"%@",difary);
        }
    }
    NSString *arystr=[difary componentsJoinedByString:@"_"];
    NSLog(@"%@",arystr);
    return  arystr;
}

方法2:字典

- (NSString *)sortStringByNumberOfWordsFromStrings:(NSString *)str
{
    NSMutableDictionary *dic=[[NSMutableDictionary alloc] init];
    NSArray *ary = [str componentsSeparatedByString:@"_"];
    NSMutableString *mystr = [[NSMutableString alloc] init];
    for (int i=0; i<ary.count; i++) {
        NSArray *ary1=[str componentsSeparatedByString:ary[i]];
        NSString *str1 = [ary1 componentsJoinedByString:nil];
        int k=(int)(str.length-str1.length)/[ary[i] length];
        NSString *set = [NSString stringWithFormat:@"%d",k];
        [dic setValue:ary[i] forKey:set];
       // NSLog(@"%@",str);
    }
 //   NSLog(@"%@",dic);
    for (int j = (int)ary.count; j>0; j--) {
       // NSLog(@"%@",[NSString stringWithFormat:@"%d",j]);
        NSString *string = [dic objectForKey:[NSString stringWithFormat:@"%d",j]];
      //  NSLog(@"%@",string);
        if (string!=nil) {
            [mystr appendString:@"_"];
            [mystr appendString:string];
        }
    }
    [mystr deleteCharactersInRange:NSMakeRange(0, 1)];
    NSLog(@"%@",mystr);
    return mystr;
}

oc将字符串中单词按照出现次数(次数都不一样)降序排序,排序之后单词只出现一次,源字符串中单词用下划线连接,生成字符串也用下滑线连接

标签:

原文地址:http://www.cnblogs.com/rainwz/p/4587640.html

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