Re: kCFCompareNumerically
Re: kCFCompareNumerically
- Subject: Re: kCFCompareNumerically
- From: Norbert Heger <email@hidden>
- Date: Tue, 15 Jan 2002 01:03:49 +0100
Ondra Cada wrote:
>
SG> Does anyone have code that will compare NSStrings numerically ie:
>
SG> Foo2.txt < Foo7.txt < Foo25.txt
>
>
...regarding this example, I guess you are after something like
>
>
NSComparisonResult numericStringCompare(NSString *a,NSString *b) {
>
int plen=[[a commonPrefixWithString:b options:0] length];
>
return [[a substringFromIndex:plen] intValue]-[[b substringFromIndex:plen]
>
intValue];
>
}
>
>
Not tested, might contain some bugs, but is simple enough to be fixed.
Obviously not tested:
- comparing "Foo1.txt" with "Foo10.txt" returns NSOrderedSame
- comparing "FooAAA.txt" with "FooBBB.txt" returns NSOrderedSame
- returning the result of an intValue subtraction does not satisfy the
required NSComparisonResult return type
However, I have to concede that the basic idea (stripping the common prefix)
is indeed a good starting point. But it turns out that the problem is not as
trivial as it seems to be at the first look, e.g. we cannot simply use the
-commonPrefixWithString:options: method. Look at the following example:
Comparing "1a" with "10a" should return NSOrderedAscending
Comparing "xa" with "x0a" should return NSOrderedDescending
Stripping the common prefix delivers the same suffixes "a" and "0a" in both
cases, and it will no longer be possible to determine the proper result.
Instead we have to strip the "non numeric common prefix".
I've attached a tested solution that seems to work properly.
Best Regards, Norbert
_____________________________________________
Norbert Heger, Objective Development
http://www.obdev.at/
[demime 0.98b removed an attachment of type application/octet-stream which had a name of NSString_ODCompareNumerically.h]
[demime 0.98b removed an attachment of type application/octet-stream which had a name of NSString_ODCompareNumerically.m]