iOS项目开发技巧iOS开发

排序中文数组 iOS

2015-12-29  本文已影响1842人  桐丘

冒泡排序方法实现数组排序,数组中元素为中文字符串,方法如下:

//数组排序
- (void)sortedArrayWithChineseObject:(NSMutableArray *)mArray {
    for(NSUInteger i = 0; i < mArray.count - 1; i++) {
        for(NSUInteger j = 0; j < mArray.count - i - 1; j++) {
            NSString *pinyinFirst = [NSString lowercaseSpellingWithChineseCharacters:mArray[j]];
            NSString *pinyinSecond = [NSString lowercaseSpellingWithChineseCharacters:mArray[j + 1]];
            //此处为升序排序,若要降序排序,把NSOrderedDescending 换为NSOrderedAscending即可。
            if(NSOrderedDescending == [pinyinFirst compare:pinyinSecond]) {
                NSString *tempString = mArray[j];
                mArray[j] = mArray[j + 1];
                mArray[j + 1] = tempString;
            }
        }
    }
    //测试
//    NSLog(@"%@", mArray);
}
//汉字转拼音,NSString的分类
#import <Foundation/Foundation.h>

@interface NSString (ChineseCharactersToSpelling)

+(NSString *)lowercaseSpellingWithChineseCharacters:(NSString *)chinese;

@end

#import "NSString+ChineseCharactersToSpelling.h"

@implementation NSString (ChineseCharactersToSpelling)

+(NSString *)lowercaseSpellingWithChineseCharacters:(NSString *)chinese {
    //转成了可变字符串
    NSMutableString *str = [NSMutableString stringWithString:chinese];
    //先转换为带声调的拼音
    CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformMandarinLatin, NO);
    //再转换为不带声调的拼音
    CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformStripDiacritics, NO);
    //返回小写拼音
    return [str lowercaseString];
}

@end

参考:
ios汉字转拼音
iOS解决NSArray、NSDictionary打印乱码问题

上一篇下一篇

猜你喜欢

热点阅读