2

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)
            i+=1;
        else if (string_rep[i]>>5==0x6)
            i+=2;
        else if (string_rep[i]>>4==0xE)
            i+=3;
        else if (string_rep[i]>>3==0x1E)
            i+=4;
        else
            //For safety
            i+=1;

        length++;
    }
}

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
2

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++;

Edit:

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

  • 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.