lukech lukech - 6 months ago 105
Objective-C Question

Sort characters in NSString into alphabetical order

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?


I think separate the string to an array of string(each string in the array contains only one char from the original string). Then sort the array will be OK. This is not efficient but is enough when the string is not very long. I've tested the code.

NSString *str = @"stack";
NSMutableArray *charArray = [NSMutableArray arrayWithCapacity:str.length];
for (int i=0; i<str.length; ++i) {
    NSString *charStr = [str substringWithRange:NSMakeRange(i, 1)];
    [charArray addObject:charStr];

NSString *sortedStr = [[charArray sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)] componentsJoinedByString:@""];