21

How to verify that a string, or a struct with only string properties, is initialised or not, inside of a mapping?

According to the docs, it means checking that the element of the mapping is at its 0-value, which is unclear to me when talking about strings.

contract C {
    mapping (address => string) m1;
    mapping (address => StringStruct) m2;
struct StringStruct {
    string someString; // Always defined when initialising this struct
    // There could be other string properties here...
}

function amIInBothMappings() returns (bool) {
     // Check that both m1[msg.sender] and m2[msg.sender].someString are non-0
}

}

In the example: what is the best way to implement amIInBothMappings that checks that msg.sender is un-initialised in both mappings m1 and m2?

Pang
  • 299
  • 1
  • 3
  • 7
lajarre
  • 385
  • 3
  • 12
  • It seems that string comparison is still manual: https://forum.ethereum.org/discussion/3238/string-compare-in-solidity . Compare the first string to the string attribute in the struct. The zero string is just '' . – Sebi Jun 05 '16 at 20:36

2 Answers2

31

One way is to check for the length of a String:

if (bytes(m1[msg.sender]).length != 0 && bytes(m2[msg.sender].someString).length != 0)
    // do your thing

See the answer I posted here

dbryson
  • 6,403
  • 2
  • 27
  • 37
0

Another way is to compare the sha3 hashes of the strings

if (sha3(myVariable) != sha3("")) {
 // is not empty string
}

However, this method is probably less efficient.

Miguel Mota
  • 5,143
  • 29
  • 47