By changing string’s case you can change its length

What will this code snippet print?

NSString *s = @"süß";
NSLog(@"%d: %@", [s length], s);
s = [s uppercaseString];
NSLog(@"%d: %@", [s length], s);

That's the thing that you should be aware of: converting string to uppercase or lowercase may change its length. It turns out that there is no capital ß letter and thus it is expanded into SS. So the printout is this:

3: süß

Why it is important? You could assume that the length will not change and cache the length of a string or ranges of some substrings. If you use these values on converted string you can get wrong results or even crash the app. The bug is so subtle that you will have hard time figuring out what's going wrong.

So just remember this thing when working with strings: by changing string's case you can change its length.

  • Digg
  • Reddit
  • StumbleUpon
  • LinkedIn
  • E-mail this story to a friend!
  • Print this article!

blog comments powered by Disqus