3

I'm trying to find out exactly how I can match the first n characters of a string with another. Here's some code I've got at the moment:

CFStringRef myStringRef = CFSTR("hello");
CFStringRef otherStringRef = CFSTR("helloworld");

CFIndex cmpChars = CFStringGetLength(myStringRef);

CFComparisonResult res = CFStringCompareWithOptions(myStringRef, otherStringRef, CFRangeMake(0, cmpChars), kCFCompareCaseInsensitive);

printf("Res: %i\n", (int)res);

I get the value of res as -1, meaning 'less than' according to the documentation. Surely though, since I specified the range to match it should only take that range into account?

benwad
  • 6,414
  • 10
  • 59
  • 93

1 Answers1

4

The documentation could be clearer, but the range is applied only to the first string, not the second. Here's a link to an old mailing list message. What you can't tell from the archive, but I know from my personal archive, is that the guy who said so was an Apple engineer.

To do what you want, you may need to use CFStringCreateWithSubstring too.

JWWalker
  • 22,385
  • 6
  • 55
  • 76
  • In case anyone is wondering, the same is true of NSString's `compare:options:range:`. https://gist.github.com/4325317 – Peter Hosey Dec 18 '12 at 05:29