I have the following function:

function getCharacterCount(string str) constant
returns (uint length)
    uint i=0;
    bytes memory string_rep = bytes(str);

    while (i<string_rep.length)
        if (string_rep[i]>>7==0)
        else if (string_rep[i]>>5==0x6)
        else if (string_rep[i]>>4==0xE)
        else if (string_rep[i]>>3==0x1E)
            //For safety


Right now it totally works for all utf-8 strings so getCharacterCount(test1234) returns 8 but getCharacterCount(test1234😂)returns 9 where I want it to return 10. I could not find any working solution for this issue.

  • It actually depends what you consider a 'char'. Technically the previous version was correct if you consider that 😂 is one unicode codepoint (char). Other emoji (eg 🇺🇬) will use two unicode codepoint; the previous version would give 2 as length for the latter while the new one would give you 4. – mirg Aug 5 '18 at 12:53
  • 1
    @mirg, They appear to be calculating the number of 16-bit words in the UTF-16 encoding of the string – ikegami Aug 5 '18 at 12:56

You are adding length once per character, so whichever case represents emojis, you need to use length++; in that case as well as the final length++;


Using else if (string_rep[i]>>3==0x1E) { i+=4; length++; } worked for me.

| improve this answer | |
  • This does work! – jasper Aug 5 '18 at 9:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.