0

I'm created a form where users can submit text to a smart contract. The text limit is 160 characters.

Some text characters / emojis are correctly counted more than once. In my form, Javascript counts this correctly.

For instance: 1️⃣is has three characters: The digit one: 1, variation selector, a Combining Enclosing Keycap.

But in Solidity, 1️⃣ is counted as 7.

pragma solidity >=0.7.0 <0.9.0;

contract MyTextCounter {
    function count(string memory text) external pure returns (uint256 count) {
        return bytes(text).length;
        // 1️⃣ outputs 7
    }
    
    function echo(string calldata text) external pure returns (string calldata textReturn) {
        return string(text);
    }
}

How can something like this be accomplished in Solidity?

2 Answers 2

2

For instance: 1️⃣is has three characters: The digit one: 1, variation selector, a Combining Enclosing Keycap.

It does have 3 characters, but they take 7 bytes.

But in Solidity, 1️⃣ is counted as 7.

You are treating the text as bytes, so it's correctly returning 7.

One option would be to count the number of bytes - instead of characters - in JS on your front end:

(new TextEncoder().encode('1️⃣')).length     // Returns 7

If that makes determining your 160 limit more complicated, you can look at how Twitter assigns "weight" to different types of characters, here -> https://developer.twitter.com/en/docs/counting-characters

0

Solidity does not have advanced unicode or string processing capabilities, so what you are asking "how" the answer is "in very difficult manner that would not make any sense."

I suggest leaving complex string processing outside the smart contracts.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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