2 iphone xcode objective-c ios
我得到一个包含以下字符串的字符串数组,字符串有一定的格式
str1 str51 str3 str4 str10 str39 str31 str191
每个字符串都以'str'开头,并在其末尾附加一个数字.
有没有一种方法来对数组进行排序,以便按值的顺序列出字符串
str1 str3 str4 str10 str31 str39 str51 str191
通过编写一些递归函数,我可以看到一种方法
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
}
Run Code Online (Sandbox Code Playgroud)
但那是非常基本的代码,Objective-C中是否有一些机制或一个很好的代码技巧来更好地处理这种排序?
非常感谢,-Code
如果它们都以相同的前缀开头,我相信默认排序会适当地处理它们.通过这个,我的意思是:
[someArray sortUsingSelector:@selector(compare:)];
Run Code Online (Sandbox Code Playgroud)
如果由于某种原因,这不起作用,那么你可以使用一个块.试试这个:
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];
}
}];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4579 次 |
| 最近记录: |