NSString has a
length property to get the number of characters.
NSString *string = @"example"; NSUInteger length = string.length; // length equals 7
As in the Splitting Example, keep in mind that
NSString uses UTF-16 to represent characters. The length is actually just the number of UTF-16 code units. This can differ from what the user perceives as characters.
Here are some cases that might be surprising:
@"é".length == 1 // LATIN SMALL LETTER E WITH ACUTE (U+00E9) @"é".length == 2 // LATIN SMALL LETTER E (U+0065) + COMBINING ACUTE ACCENT (U+0301) @"❤️".length == 2 // HEAVY BLACK HEART (U+2764) + VARIATION SELECTOR-16 (U+FE0F) @"🇮🇹".length == 4 // REGIONAL INDICATOR SYMBOL LETTER I (U+1F1EE) + REGIONAL INDICATOR SYMBOL LETTER T (U+1F1F9)
In order to get the number of user-perceived characters, known technically as "grapheme clusters", you must iterate over the string with
-enumerateSubstringsInRange:options:usingBlock: and keep a count. This is demonstrated in an answer by Nikolai Ruhe on Stack Overflow.