将NSString中的字符按字母顺序排序 [英] Sort characters in NSString into alphabetical order

查看:241
本文介绍了将NSString中的字符按字母顺序排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将单词重新排列为字母顺序.例如,番茄会变质,或者堆栈会变味.

I'm trying to re-arrange words into alphabetical order. For example, tomato would become amoott, or stack would become ackst.

我已经找到了一些用char数组在C语言中执行此操作的方法,但是我在使它在NSString对象的范围内工作方面遇到了问题.

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.

在NSString对象本身中是否有更简单的方法?

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:@""];

这篇关于将NSString中的字符按字母顺序排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆