Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 C with char arrays, but I'm having issues getting that to work within the confines of the NSString object.

Is there an easier way to do it within the NSString object itself?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
517 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...