• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Re: NSString comparing alphanumerically (with numbers)
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: NSString comparing alphanumerically (with numbers)


  • Subject: Re: NSString comparing alphanumerically (with numbers)
  • From: Andreas Schwarz <email@hidden>
  • Date: Wed, 22 May 2002 10:07:51 -0700

(I hope someone will have a hint on this one, unless I'm now banned
completely ;-))
Is there a direct/simple way to compare two NSStrings (during a sort),
while keeping numbers as numbers
mixed with text ? (ie toto1 < toto2 < toto10 and not toto1 < toto10 <
toto2 ) ?

what would be the best *cocoa* way to do it ? (Or should I compare each
character myself?)
(neither caseInsensitiveCompare nor NSLiteralSearch do the job)

Here are parts of an NSString category I've got that should do the job for you. I believe this is what the Finder uses to do its sorting, as well.


@implementation NSString (SomeSortStuff)

static UCCollateOptions opts = (kUCCollateComposeInsensitiveMask |
kUCCollateWidthInsensitiveMask |
kUCCollateCaseInsensitiveMask |
kUCCollateDigitsOverrideMask |
kUCCollateDigitsAsNumberMask |
kUCCollatePunctuationSignificantMask);

- (NSComparisonResult)filenameCompareWithString:(NSString *)string {
NSData *selfString = [self dataUsingEncoding:NSUnicodeStringEncoding];
NSData *otherString = [string dataUsingEncoding:NSUnicodeStringEncoding];
SInt32 order;

UCCompareTextDefault(opts, (unichar *)[selfString bytes], [self length], (unichar *)[otherString bytes], [string length], NULL, &order);

if (order < 0) return NSOrderedAscending;
if (order == 0) return NSOrderedSame;
else if (order > 0) return NSOrderedDescending;

return [self caseInsensitiveCompare:string];
}

@end


Enjoy,
Andreas Schwarz
http://homepage.mac.com/schwarz
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives: http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.

  • Prev by Date: validateMenuItem: issues
  • Next by Date: Re: keybinding and getting keyDown for entire app
  • Previous by thread: Re: NSString comparing alphanumerically (with numbers)
  • Next by thread: Re: didEndShouldCloseSheet]
  • Index(es):
    • Date
    • Thread