Created
May 19, 2018 08:01
-
-
Save rickytan/380900635bc9b63511c072e783626189 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@interface NSString (ComposedCharacter) | |
/** | |
* @description @b NSString use UTF-16 encode to store characters internally, in | |
* most cast, the @c length of a @b NSString is the number visible characters. | |
* But not for some special Characters like Emoji. | |
* @"ππ€‘βΉπΏββοΈβ«οΈπ€₯π€πͺπΎ" this @b NSString only has 7 Emojis, but its @c length is | |
* 20. Sometimes we only want the human visible charater count. | |
* | |
* @code | |
* @"ππ€‘βΉπΏββοΈβ«οΈπ€₯π€πͺπΎ".length == 20 | |
* @"ππ€‘βΉπΏββοΈβ«οΈπ€₯π€πͺπΎ".rt_composedCharacterLength == 7 | |
* | |
* ++ ++ ++++++ ++ ++ ++ ++++ | |
* π π€‘ βΉπΏββοΈ β«οΈ π€₯ π€ πͺπΎ | |
* @endcode | |
* | |
* | |
* @return number of visible charaters | |
* @warning Emoji is System sensitive, and its behavior differ on different | |
* systems, so dose this property. | |
*/ | |
@property (nonatomic, assign, readonly) NSUInteger rt_composedCharacterLength; | |
@end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@implementation NSString (ComposedCharacter) | |
- (NSUInteger)rt_composedCharacterLength __attribute((const)) | |
{ | |
NSUInteger numberOfComposedCharaters = 0; | |
NSUInteger length = self.length; | |
while (length > 0) { | |
NSRange range = [self rangeOfComposedCharacterSequenceAtIndex:length - 1]; | |
length -= range.length; | |
++ numberOfComposedCharaters; | |
} | |
return numberOfComposedCharaters; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment