Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number of characters in an NSString

I need a way to find the number of characters in an NSString. The nature of my app requires many multi char unicode characters, which presents obvious problems for the length method on NSString.

Copied from Apple's developer website:

Length  
Returns the number of Unicode characters in the receiver. 
- (NSUInteger)length  
Return Value The number of Unicode characters in the receiver.

I do not want the number of characters per se, but rather the number of characters that you would see if the string were printed out. Some characters I use in the app are numbers and letters with overlines, i.e. 0̄ . In unicode, this is represented with two separate unicode characters, however, when printed, is a single entity. When finding the length of the string, I need characters such as 0̄ to only count as one, not two as it would with the NSString length method. Is there a way of doing this? Thanks.

like image 728
Iowa15 Avatar asked Mar 22 '14 18:03

Iowa15


1 Answers

You can enumerate the characters in the string with the NSStringEnumerationByComposedCharacterSequences option:

NSString *string = @"0̄ 😄";
__block NSUInteger count = 0;
[string enumerateSubstringsInRange:NSMakeRange(0, [string length])
                           options:NSStringEnumerationByComposedCharacterSequences
                        usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
                            count++;
                        }];
NSLog(@"%ld %ld", (long)count, (long)[string length]);
// Output: 3 5

Both the decomposed character 0̄ and the Emoji 😄 (which is also stored as two UTF-16 characters – a so-called "surrogate pair") are counted as one.

like image 149
Martin R Avatar answered Nov 04 '22 12:11

Martin R