5

For example I have following string, which will be given as input from a user:

string str = "0-00:03"

Inside my contract I would like to check that:

  • str[1] should be -
  • str[4] should be :
  • and the remaining characters have to be numeric value.

This operation is easy to do C where with pointer I can iterate each character and check its char value. But I was not able to operate this inside my contract under Solidity language.

alper
  • 8,395
  • 11
  • 63
  • 152

1 Answers1

5

Just cast the string to bytes

function testStr(string str) constant returns (bool) {
    bytes memory b = bytes(str);
    if (b.length != 7)
        return false;
    for (uint i; i < 7; i++) {
        if (i==1) {
            if(b[i] != 45) return false;
        }
        else if (i == ) {
            if(b[i] != 58) return false;
        }
        else if(b[i] < 48 || b[i] > 57)
            return false;
    }
    return true;
}
alper
  • 8,395
  • 11
  • 63
  • 152
Tjaden Hess
  • 37,046
  • 10
  • 91
  • 118
  • Thank you. Also for example when it pass the test, I would like to convert "03" into a uint32 variable. The thing come to my mind is: 010 + 31 <= 3. So can I do something like: (b[i] - 48) * 10 and cast result into uint32?@Tjaden Hess – alper Apr 10 '17 at 22:30
  • 1
    Sounds about right – Tjaden Hess Apr 10 '17 at 23:00