NSString Length - Special Characters

I have a UITextField into which characters will be entered. It is as simple as I can return its actual length? When a string contains AZ 1-9 characters, it works as expected, but any emojis or special characters get a double count.

It has the simplest format, it just has 2 characters for some special characters, such as emoji:

 NSLog(@"Field '%@' contains %i chars", myTextBox.text, [myTextBox.text length] ); 

I tried scrolling every character with characterAtIndex , substringFromIndex , etc. and didnโ€™t get anywhere.

According to the answer below, the exact code is used to count the characters (I hope this is the correct approach, but it works ..):

 NSString *sString = txtBox.text; __block int length = 0; [sString enumerateSubstringsInRange:NSMakeRange(0, [sString length]) options:NSStringEnumerationByComposedCharacterSequences usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) { length++; }]; NSLog(@"Total: %u", length ); 
+8
objective-c uitextfield special-characters nsstring
source share
2 answers

[myTextBox.text length] returns the number of unichars, not the visible length of the string. รฉ = e+ยด , which is equal to 2 unichars. Emoji characters must contain more than 1 unichar.

This example below lists through each block of characters in a string. This means that if you register the substringRange range, it can be greater than 1.

 __block NSInteger length = 0; [string enumerateSubstringsInRange:range options:NSStringEnumerationByComposedCharacterSequences usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) { length++; }]; 

You should go and see Session 128 - Text Processing with 2011 WWDC. They explain why this is so. It's really cool!

Hope this was for any help. Hooray!

+12
source share

We can also consider the option below as a solution.

 const char *cString = [myTextBox UTF8String]; int textLength = (int)strlen(cString); 

This will work with special characters and emoji.

0
source share

All Articles