You could store each of the string's characters into an NSArray
of NSNumber
objects and then sort that. Seems a bit expensive, so I would perhaps just use qsort()
instead.
Here it's provided as an Objective-C category (untested):
NSString+SortExtension.h:
#import <Foundation/Foundation.h>
@interface NSString (SortExtension)
- (NSString *)sorted;
@end
NSString+SortExtension.m:
#import "NSString+SortExtension.h"
@implementation NSString (SortExtension)
- (NSString *)sorted
{
// init
NSUInteger length = [self length];
unichar *chars = (unichar *)malloc(sizeof(unichar) * length);
// extract
[self getCharacters:chars range:NSMakeRange(0, length)];
// sort (for western alphabets only)
qsort_b(chars, length, sizeof(unichar), ^(const void *l, const void *r) {
unichar left = *(unichar *)l;
unichar right = *(unichar *)r;
return (int)(left - right);
});
// recreate
NSString *sorted = [NSString stringWithCharacters:chars length:length];
// clean-up
free(chars);
return sorted;
}
@end
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…