冒泡排序方法實現(xiàn)數(shù)組排序嫉到,數(shù)組中元素為中文字符串,方法如下:
//數(shù)組排序
- (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);
}
//漢字轉(zhuǎn)拼音践剂,NSString的分類
#import <Foundation/Foundation.h>
@interface NSString (ChineseCharactersToSpelling)
+(NSString *)lowercaseSpellingWithChineseCharacters:(NSString *)chinese;
@end
#import "NSString+ChineseCharactersToSpelling.h"
@implementation NSString (ChineseCharactersToSpelling)
+(NSString *)lowercaseSpellingWithChineseCharacters:(NSString *)chinese {
//轉(zhuǎn)成了可變字符串
NSMutableString *str = [NSMutableString stringWithString:chinese];
//先轉(zhuǎn)換為帶聲調(diào)的拼音
CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformMandarinLatin, NO);
//再轉(zhuǎn)換為不帶聲調(diào)的拼音
CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformStripDiacritics, NO);
//返回小寫拼音
return [str lowercaseString];
}
@end