字符串压缩算法

    NSMutableString * str = [[NSMutableString alloc]initWithString:string];
    NSMutableString * str1 = [[NSMutableString alloc]init];
    NSMutableString * str2 = [[NSMutableString alloc]init];
    NSMutableArray * array = [[NSMutableArray alloc]initWithObjects:str, nil];
    SEL sel = @selector(compare:);
    NSArray * array1 =[array sortedArrayUsingSelector:sel];
    //NSLog(@"%@",array1);打印测试
    
    for (NSInteger i = 0; i < str.length; i++) {
        int n = 1;
        for (NSInteger j = i+1; j < str.length - 1; j++) {
    
            unichar ch1 = [str characterAtIndex:i];
            unichar ch2 = [str characterAtIndex:j];
        if(ch1 == ch2 )
        {
            n++;
        }else if(ch1 != ch2)
        {
            if(n==1)
            {
            [str1 setString:[NSString stringWithFormat:@"%c",ch1]];
            }
            else
            {
            [str1 setString:[NSString stringWithFormat:@"%c%d",ch1,n]];
            }
            [str2 appendString:str1];
            break;
        }
        }
    }
  
    NSLog(@"%@",str2);
    return str2;

你可能感兴趣的:(压缩,算法,String,Objective-C,NSMutableArray)