当前位置:   article > 正文

将一个字符串中的字符按照ASCII码从小到大的顺序排序_将字符串s中的所有字符按ascii值从小到大排序

将字符串s中的所有字符按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;
}

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/310081
推荐阅读
相关标签
  

闽ICP备14008679号