1. 程式人生 > >首字元字典順序(ascii 值大小)排序

首字元字典順序(ascii 值大小)排序

//  Copyright (c) 2015年 JWC. All rights reserved.

 傳入:@"Lifeislikeridingabicycletokeepyourblanceyoumustkeepmoving"
 返回:@"Laabbcccdeeeeeeeefggiiiiiiikkklllmmnnnoooopprrssttuuuvyyy"
 */
-(NSString *)sortString:(NSString *)str{
    NSMutableString *muString = [NSMutableString stringWithString:str];
    //氣泡排序
    for (int i = 0; i < muString.length - 1; i++) {
        
        for (int j = 0; j < muString.length - i - 1; j++) {
            if ([muString characterAtIndex:j] > [muString characterAtIndex:j+1]) {
                //把第j+1的值取出來賦值給p
                unichar p = [muString characterAtIndex: j+1];
                //用第j為替換第j+1位
                [muString replaceCharactersInRange:NSMakeRange(j+1, 1) withString:[NSString stringWithFormat:@"%c",[muString characterAtIndex:j]] ];
                //用第j+1位的值替換給第j位,完成交換
                [muString replaceCharactersInRange:NSMakeRange(j, 1) withString:[NSString stringWithFormat:@"%c",p]];
                
            }
        }
    }

    return muString;
}