Skip to content

Instantly share code, notes, and snippets.

@mdippery
Created March 31, 2011 17:21
Show Gist options
  • Save mdippery/896807 to your computer and use it in GitHub Desktop.
Save mdippery/896807 to your computer and use it in GitHub Desktop.
String sorting example in Objective-C
#import <Foundation/Foundation.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
static int compare_char(const char *a, const char *b)
{
if (*a > *b) {
return 1;
} else if (*a < *b) {
return -1;
} else {
return 0;
}
}
@interface NSString (Sorting)
- (NSString *)stringBySortingCharacters;
@end
@implementation NSString (Sorting)
- (NSString *)stringBySortingCharacters
{
const char *s = [self UTF8String];
char *s2 = (char *) calloc([self length]+1, 1);
if (!s2) return nil;
strncpy(s2, s, [self length]);
qsort(s2, [self length], 1, compare_char);
NSString *ret = [NSString stringWithUTF8String:s2];
free(s2);
return ret;
}
@end
int main(int argc, char **argv)
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSString *s1 = @"string";
NSString *s2 = @"the quick brown fox jumps over the lazy dog";
printf("Sorted: %s\n", [[s1 stringBySortingCharacters] UTF8String]);
printf("Sorted: %s\n", [[s2 stringBySortingCharacters] UTF8String]);
[pool release];
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment