Detecting if a character in a String is an emoticon (using Android)

后端 未结 3 1173
庸人自扰
庸人自扰 2021-01-05 07:54

Like the title says. I want to find out if a given java String contains an emoticon.

I can\'t use Character.UnicodeBlock.of(char) == Character.UnicodeBlock.EMO

3条回答
  •  走了就别回头了
    2021-01-05 08:10

    I was in fact able to use the linked iOS code to create the following function. I didn't realize that a String that contains, for example, a single emoticon will have a length of 2. So you can check if a character is in fact a surrogate.

    I'm not entirely sure how to handle else if (substring.length > 1) from the iOS code but I think Character.isHighSurrogate(myChar) does the same job in that instance.

    private boolean containsIllegalCharacters(String displayName)
    {
        final int nameLength = displayName.length();
    
        for (int i = 0; i < nameLength; i++)
        {
            final char hs = displayName.charAt(i);
    
            if (0xd800 <= hs && hs <= 0xdbff)
            {
                final char ls = displayName.charAt(i + 1);
                final int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
    
                if (0x1d000 <= uc && uc <= 0x1f77f)
                {
                    return true;
                }
            }
            else if (Character.isHighSurrogate(hs))
            {
                final char ls = displayName.charAt(i + 1);
    
                if (ls == 0x20e3)
                {
                    return true;
                }
            }
            else
            {
                // non surrogate
                if (0x2100 <= hs && hs <= 0x27ff)
                {
                    return true;
                }
                else if (0x2B05 <= hs && hs <= 0x2b07)
                {
                    return true;
                }
                else if (0x2934 <= hs && hs <= 0x2935)
                {
                    return true;
                }
                else if (0x3297 <= hs && hs <= 0x3299)
                {
                    return true;
                }
                else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50)
                {
                    return true;
                }
            }
        }
    
        return false;
    }
    

提交回复
热议问题