关闭

使用CFStringTransform方便的进行中文名字的排序

标签: 中文排序名字排序
42人阅读 评论(0) 收藏 举报

#import <Foundation/Foundation.h>


@interface NSArray (chinese)


+(NSArray *)sortedArrayByChinese: (NSArray*) array;


@end


@interface Common_Manage : NSObject


+ (NSComparisonResult) CompareString: (NSString*) strSrc with:(NSString*) str2; 


@end



#import "Common_Manage.h"


@implementation Common_Manage


+(NSComparisonResult)CompareString:(NSString *)strSrc with:(NSString *)str2{

    CFStringRef cfstringSrc = CFStringCreateWithCString(NULL, strSrc.UTF8String, kCFStringEncodingUTF8);

    CFMutableStringRef src = CFStringCreateMutableCopy(NULL, 0, cfstringSrc);

    CFStringTransform(src, 0, kCFStringTransformToLatin, false);

    CFStringTransform(src, 0, kCFStringTransformStripCombiningMarks, false);

    

    CFStringRef cfstringto = CFStringCreateWithCString(NULL, str2.UTF8String, kCFStringEncodingUTF8);

    CFMutableStringRef srcto = CFStringCreateMutableCopy(NULL, 0, cfstringto);

    CFStringTransform(srcto, 0, kCFStringTransformToLatin, false);

    CFStringTransform(srcto, 0, kCFStringTransformStripCombiningMarks, false);

    

    CFComparisonResult result = CFStringCompare(src, srcto, kCFCompareCaseInsensitive);

    NSComparisonResult r = (NSComparisonResult)result;

    return r;

}


@end


@implementation NSArray (chinese)


+(NSArray*) sortedArrayByChinese: (NSArray*) array

{

    NSArray* ret = [array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {

        NSComparisonResult ret = [Common_Manage CompareString:obj1 with:obj2];

        return ret;

    }];

    

    return ret;

}


@end



********************使用*********************

NSArray *array = [[NSArray alloc]initWithObjects:@"阿诶",@"啊啊",@"刘扬",@"刘江", nil];

    NSArray *sorted = [array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {

        NSString *name1 = obj1;

        NSString *name2 = obj2;

        NSComparisonResult e = [Common_Manage CompareString:name1 with:name2];

        return e;

    }];

    for (int i = 0; i < [array count]; i++) {

        NSLog(@"%@",[sorted objectAtIndex:i]);

    }


备注:来源于http://blog.csdn.net/chiyun1/article/details/45042105



0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:43次
    • 积分:2
    • 等级:
    • 排名:千里之外
    • 原创:0篇
    • 转载:1篇
    • 译文:0篇
    • 评论:0条
    文章存档