Sort characters in NSString into alphabetical order

前端 未结 4 1119
醉话见心
醉话见心 2020-12-10 15:57

I\'m trying to re-arrange words into alphabetical order. For example, tomato would become amoott, or stack would become ackst.

I\'ve found some methods to do this in

4条回答
  •  眼角桃花
    2020-12-10 16:43

    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 
    
    @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
    

提交回复
热议问题