按字符串值对字符串的NSMutableArray进行排序

编程入门 行业动态 更新时间:2024-10-27 14:30:56
本文介绍了按字符串值对字符串的NSMutableArray进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我得到一个包含以下字符串的字符串数组,字符串有一定的格式

I get an array of strings with the following strings, there is a certain patern to the strings

str1 str51 str3 str4 str10 str39 str31 str191

str1 str51 str3 str4 str10 str39 str31 str191

每个字符串以'str'开头并附加一个数字

Every string starts with 'str' and has a number appended onto the end of it.

是否有一种排序数组的方法,因此它按值的顺序列出字符串

Is there a neath way to sort the array so it lists the strings in order of value

str1 str3 str4 str10 str31 str39 str51 str191

str1 str3 str4 str10 str31 str39 str51 str191

我可以通过编写一些递归函数来看到这样做的方法

I can see a way to do it by writing some recursive function that will

NSString * firstString = [[strArray objectAtIndex:i].substringFromIndex:3]; NSString * secondString = [[strArray objectAtIndex:i+1].substringFromIndex:3]; if ([firstString intValue] < [secondString intValue]) { //do nothing they order is correct } else { //swap the order of the 2 strings in the array }

但那是非常基本的代码,Objective-C中是否有一些机制或一个很好的代码技巧来更好地处理这种排序?

But thats very rudimentary code, Is there some mechanism in Objective-C or a nice code trick to handle this sorting better?

非常感谢, -Code

Many Thanks, -Code

推荐答案

如果它们都以相同的前缀开头,我相信默认排序会适当地处理它们。我的意思是:

If they all start with the same prefix, I believe that the default sort will handle them appropriately. By this, I mean:

[someArray sortUsingSelector:@selector(compare:)];

如果由于某种原因,这不起作用,那么你可以使用一个块。试试这个:

If, for some reason, this isn't working, then you can use a block. Try this:

NSArray *sortedArray = [someArray sortedArrayUsingComparator:^NSComparisonResult(id a, id b) { //Default compare, to protect against cast if (![a isKindOfClass:[NSString class]] || ![b isKindOfClass:[NSString class]]) { return ([a compare:b]); } else { NSString *aString = (NSString*) a; NSString *bString = (NSString*) b; int aInt = [[a.substringFromIndex:3] intValue]; int bInt = [[b.substringFromIndex:3] intValue]; return [aInt < bInt]; } }];

更多推荐

按字符串值对字符串的NSMutableArray进行排序

本文发布于:2023-10-18 03:27:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1502946.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   字符串值   NSMutableArray

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!