Solidity String Length – How to Check String Length in a Contract

soliditystring

I want to sent a string as an argument to a function. But some user may enter maybe 100 size string or even larger.

[Q] Inside the function is it possible to check the size of the string and return false if it exceeds the length limit that I have specified.

For example, a user is only allowed to send string which has length of 64 characters, and the contract's function returns throw if the string exceeds the limit of 64 character.

Test.transaction().setVariable("very_large_size_string_entered_65_chars");

For example:

Contract Test{
   String data;
   function setVariable(string str) {
       //check somehow does the string exceeds the character limit.
       data = str;
   }
}

Thank you for your valuable time and help.

Best Answer

Just check if bytes(str).length is too big.

Mind: This does not show the number of characters! See the answer below if you need to know an exact length of a utf-8 encoded string. This will cost significantly more gas, however. Note that the utf-8 length will be at most the byte length.