对不基于字符串的字符串 nsarray 进行排序
所以我有一个从网络服务中检索的数组,没有特定的顺序
示例:
0 => x large,
1 => large,
2 => XX large,
3 => small,
4 => medium,
5 => x small
我需要对它们进行排序:首先基于特定的 - 这可能是反向字母顺序:
small
medium
large
其次我需要根据它们的“x”对应部分对它们进行排序:
x small
small
medium
large
x large
xx large
我知道我可以通过强力字符串匹配来做到这一点,但我真的很想知道如何整齐地做到这一点,也许是正则表达式或更优雅的东西?
So i have an array that i retrieve from a web service in no particular order
example:
0 => x large,
1 => large,
2 => XX large,
3 => small,
4 => medium,
5 => x small
I need to sort them: firstly based on specific - which could be reverse alphabetic:
small
medium
large
Secondly i need to sort them based on their 'x' counter parts:
x small
small
medium
large
x large
xx large
I know i can do this with brute force string matching but i would really like a suggestion on how to do this tidily, perhaps a regex or something more elegant?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用 NSComparator 块语法。 。
在第二种方法中,我添加了 Web 服务器发送的数字和 x 大小之间的映射 现在
[obj size];
假设返回一个 NSNumber 对象。该问题的第二个任务——分组为小型、中型、大型——可以这样完成:
Use NSComparator block syntax. Something like
In the second approach I added a mapping between the numbers send by the web server and the x-sizes. Now
[obj size];
is suppose to return a NSNumber object.The second task of the question — the grouping into small, medium, large — could be done like this:
首先,为了理智起见,向 NSString 添加一个类别
然后,
我不会称其为优雅,但这是我能想到的最简单的答案。您可能想颠倒顺序以满足您的需要 - 只需对比较结果应用负数即可。如果这不起作用请评论,我会再看一下。
First, add a category to NSString for sanity's sake
Then,
I wouldn't call it elegant, but it's the simplest answer I could think of. You may want to reverse the ordering to suit your needs - just apply negative to comparison result. Comment if this doesn't work out, and I'll give it another look.
也许您可以对字符串进行排序,其中“xx s”被“z”替换,“x s”被“v”替换,“x l”被“b”替换,“xx l”被“a”替换。
q
maybe you can sort your strings where "xx s" was replaced by "z", "x s" was replaced by "v" and "x l" replaced with "b" and "xx l" with "a".
q