Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 215
Luke Avatar asked Nov 13 '12 10:11

Luke


3 Answers

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
like image 155
trojanfoe Avatar answered Nov 15 '22 22:11

trojanfoe


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:@""];
like image 21
sunkehappy Avatar answered Nov 15 '22 23:11

sunkehappy


// --------- Function To Make an Array from String
NSArray *makeArrayFromString(NSString *my_string) {
    NSMutableArray *array = [[NSMutableArray alloc] init];
    for (int i = 0; i < my_string.length; i ++) {
        [array addObject:[NSString stringWithFormat:@"%c", [my_string characterAtIndex:i]]];
    }
    return array;

}

// --------- Function To Sort Array
NSArray *sortArrayAlphabetically(NSArray *my_array) {
    my_array= [my_array sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
    return my_array;
}

// --------- Function Combine Array To Single String
NSString *combineArrayIntoString(NSArray *my_array) {
    NSString * combinedString = [[my_array valueForKey:@"description"] componentsJoinedByString:@""];
    return combinedString;
}




// Now you can call the functions as in below where string_to_arrange is your string
    NSArray *blowUpArray;
    blowUpArray = makeArrayFromString(string_to_arrange);
    blowUpArray = sortArrayAlphabetically(blowUpArray);
    NSString *arrayToString= combineArrayIntoString(blowUpArray);
    NSLog(@"arranged string = %@",arrayToString);
like image 25
U.F. Okechukwu Avatar answered Nov 15 '22 23:11

U.F. Okechukwu