Solidity

在字元串可靠性中查找單詞

  • March 13, 2022

如何查找某個單詞是否是solidity 字元串的一部分?假設有人將字元串上傳到智能合約,該字元串必須包含單詞“solidity”才能被函式接受。是否可以創建一個修飾符或 require() 檢查來確保這一點?

modifier contains (string memory what, string memory where) {
   bytes memory whatBytes = bytes (what);
   bytes memory whereBytes = bytes (where);

   require(whereBytes.length >= whatBytes.length);

   bool found = false;
   for (uint i = 0; i <= whereBytes.length - whatBytes.length; i++) {
       bool flag = true;
       for (uint j = 0; j < whatBytes.length; j++)
           if (whereBytes [i + j] != whatBytes [j]) {
               flag = false;
               break;
           }
       if (flag) {
           found = true;
           break;
       }
   }
   require (found);

   _;
}

function foo (string memory str) public contains ("solidity", str) {
   ...
}

引用自:https://ethereum.stackexchange.com/questions/69307