Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
352 views
in Technique[技术] by (71.8m points)

iphone - I have an NSArray on NSString's, but some of the strings are only numbers. How do I sort numerically properly?

My NSArray contains 100, 110, 91, 98, and 87, all NSStrings.

I'd like to sort them to show up in this order: 87, 91, 98, 100, 110.

Instead they are showing up as 100, 110, 87, 91, 98.

I can't start the array with all ints instead of strings unfortunately. Anyone have any ideas on how to tell if the array contains ONLY numbers from strings, maybe using a for loop? Then I could just convert them all to ints within the array and do the sort that way. Or maybe there is an easy way I am missing?

Let me know if anyone has any ideas.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use the NSNumericSearch option to the NSString compare function to sort strings numerically. To do this with an NSArray, you will need to write a block or function to call the compare:options: method.

NSArray *theStrings; // Contains strings, some of which are numbers
NSArray *theSortedStrings = [theStrings sortedArrayUsingComparator:^(id obj1, id obj2) {
    return [(NSString *)obj1 compare:(NSString *)obj2 options:NSNumericSearch];
}];

This will also sort numerically if there is a numer within a string, i.e. "abcd89" will come before "abcd123".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

Just Browsing Browsing

[6] html - How to create even cell spacing within a

1.4m articles

1.4m replys

5 comments

57.0k users

...