如何在Objective-C的字符串进行排序? [英] How to sort a string of characters in objective-C?
问题描述
我在找一个字符串中的字符排序的Objective-C的方法,因为每个答案<一个href="http://stackoverflow.com/questions/401834/how-to-elegantly-compute-the-anagram-signature-of-a-word-in-ruby">this的问题。
在理想情况下一个函数,它接受一个NSString并返回排序相同。
此外,我想运行长度EN code的3个或更多的重复序列。因此,例如密西西比第一次变为iiiimppssss,然后可以通过编码被缩短为4impp4s
我不是专家在Objective-C(以上Java和C ++背景),所以我也很喜欢一些线索,什么是处理内存管理的最佳实践(保留数等 - 不GC上的iPhone ),用于这种功能的返回值。我的源字符串是一个iPhone搜索栏控制,因此是一个的NSString *
。
INT char_compare(为const char *一,为const char * B){
如果(* A&LT; * B){
返回-1;
}否则,如果(* A&GT; * B){
返回1;
} 其他 {
返回0;
}
}
的NSString * sort_str(的NSString *未排序){
INT LEN = [未分类的长度] + 1;
字符* CSTR =的malloc(LEN);
[无序getCString:CSTR最大长度:LEN编码:NSISOLatin1StringEncoding]。
的qsort(CSTR,LEN - 1,的sizeof(炭),char_compare);
的NSString *排序= [NSString的stringWithCString:CSTR编码:NSISOLatin1StringEncoding]。
免费(CSTR);
返回排序;
}
返回值会被自动释放,所以如果你想留住它的调用者,你需要把它保留下来。不统一code安全。
I'm looking for an Objective-C way of sorting characters in a string, as per the answer to this question.
Ideally a function that takes an NSString and returns the sorted equivalent.
Additionally I'd like to run length encode sequences of 3 or more repeats. So, for example "mississippi" first becomes "iiiimppssss", and then could be shortened by encoding as "4impp4s".
I'm not expert in Objective-C (more Java and C++ background) so I'd also like some clue as to what is the best practice for dealing with the memory management (retain counts etc - no GC on the iphone) for the return value of such a function. My source string is in an iPhone search bar control and so is an NSString *
.
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 autoreleased so if you want to hold on to it in the caller you'll need to retain it. Not Unicode safe.
这篇关于如何在Objective-C的字符串进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!