Skip to content

Instantly share code, notes, and snippets.

@rickytan
Created May 19, 2018 08:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rickytan/380900635bc9b63511c072e783626189 to your computer and use it in GitHub Desktop.
Save rickytan/380900635bc9b63511c072e783626189 to your computer and use it in GitHub Desktop.
@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
@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