冒泡排序方法实现数组排序,数组中元素为中文字符串,方法如下:
//数组排序
- (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
网友评论
NSArray *array = @[@"十九大", @"高铁", @"主席", @"人大代表", @"环保"];
NSArray *sortedArray1 = [array sortedArrayUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {
return [obj2 compare:obj1];
}];
NSLog(@"%@", sortedArray1);
打印结果是(
"高铁",
"环保",
"十九大",
"人大代表",
"主席",
)