How do I sort a character string in objective-C?
I'm looking for a way to sort Objective-C characters in a string, as per the answer to this question.
Ideally, a function that takes an NSString and returns the sorted equivalent.
Also, I would like to run sequences of lengths of 3 or more repetitions. For example, "Mississippi" first becomes "iiiimppssss" and can then be abbreviated by encoding "4impp4s".
I am not an Objective-C expert (more background in Java and C ++), so I would also like to know what is best for memory management (store counts, etc. - no GC on iphone) for a return value like this functions. My original string is in the iPhone's search bar control bar as well NSString *
.
source to share
int char_compare(const char* a, const char* b) {
if(*a < *b) {
return -1;
} else if(*a > *b) {
return 1;
} else {
return 0;
}
}
NSString *sort_str(NSString *unsorted) {
int len = [unsorted length] + 1;
char *cstr = malloc(len);
[unsorted getCString:cstr maxLength:len encoding:NSISOLatin1StringEncoding];
qsort(cstr, len - 1, sizeof(char), char_compare);
NSString *sorted = [NSString stringWithCString:cstr encoding:NSISOLatin1StringEncoding];
free(cstr);
return sorted;
}
The return value is auto-implemented, so if you want to store it in the caller, you need to store it. Unsafe Unicode.
source to share
With a limited set of code, sorting is best suited:
NSString * sortString(NSString* word) {
int rads[128];
const char *cstr = [word UTF8String];
char *buff = calloc([word length]+1, sizeof(char));
int p = 0;
for(int c = 'a'; c <= 'z'; c++) {
rads[c] = 0;
}
for(int k = 0; k < [word length]; k++) {
int c = cstr[k];
rads[c]++;
}
for(int c = 'a'; c <= 'z'; c++) {
int n = rads[c];
while (n > 0) {
buff[p++] = c;
n--;
}
}
buff[p++] = 0;
return [NSString stringWithUTF8String: buff];
}
Note that the above example only works for lowercase letters (copied from a specific application that needs to sort lowercase strings). To expand it to handle all ASCII 127, just do for (c = 0; c <= 127; C ++).
source to share