Jeff's Cocoa Journal
        

Comparing NSStrings numerically

Sometimes it is desirable to compare strings with numbers as part of the string. For example, a list of filenames might be:

    pic1.gif, pic8.gif, pic9.gif, pic12.gif

The basic compare message for NSString, compare:, only treats the numbers as a string of characters rather than as numbers. This causes the above list to be sorted as:

    pic1.gif, pic12.gif, pic8.gif, pic9.gif
What is necessary is a new message for NSString which can identify the numbers in the string and sort them accordingly.

Categories provide a way to add new methods to existing classes even if you do not have the source code to the original class. I created a category on NSString called numericalCompare: (originally I called it smartCompare:). It will sort our list of filenames as we expect:

    pic1.gif, pic8.gif, pic9.gif, pic12.gif
numericalCompare: also supports strings with multiple, separate numbers. For example it will sort a list of strings as:
    abc123def456, abc123def457, abc234def456, def456ghi789

My code is a direct translation of the algorithm I devised to perform the comparison and makes extensive use of NSScanner. However, it is somewhat inefficient as it stands. Fortunately, Norbert Heger provided a much more efficient routine to perform the same action.

Here is the source code for numericalCompare: NumericalCompare.sit.hqx. NumericalCompare.h is the header file declaring the category. NumericalCompare.m is the definition of numericalCompare:. NorbertCompare.m is Norbert Heger's version of numericalCompare:.



© Copyright 2002 Jeff Gilbert. Click here to send an email to the editor of this weblog.
Last update: 6/3/02; 10:18:40 PM.