22

How can you check if a type string is empty in Solidity?

For instance this would work when testing if a string was initialized to have no characters:

string public emptyStringTest = '';

or when you would like to test if a mapping(bytes32 => string) has a key that is initialized.

mapping(bytes32 => string) emptyStringTest;
0

1 Answer 1

40

You can convert the string into a type bytes and then check its length.

For example this will test if emptyStringTest is indeed an empty string:

bytes memory tempEmptyStringTest = bytes(emptyStringTest); // Uses memory
if (tempEmptyStringTest.length == 0) {
    // emptyStringTest is an empty string
} else {
    // emptyStringTest is not an empty string
}

Info on the memory keyword

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