Submission 8f622e49...

ChallengeString search
Submitter0x01a32b7b34a870d...
Submitted at2018-57-14
Gas used1406911
/**
 * This file is part of the 1st Solidity Gas Golfing Contest.
 *
 * This work is licensed under Creative Commons Attribution ShareAlike 3.0.
 * https://creativecommons.org/licenses/by-sa/3.0/
 */

pragma solidity 0.4.24;

contract IndexOf {
    /**
     * @dev Returns the index of the first occurrence of `needle` in `haystack`,
     *      or -1 if `needle` is not found in `haystack`.
     *
     * Input strings may be of any length <2^255.
     *
     * @param _haystack The string to search.
     * @param _needle The string to search for.
     * @return The index of `needle` in `haystack`, or -1 if not found.
     */
    function indexOf(string _haystack, string _needle) public pure returns(int) {
      bytes memory haystack = bytes(_haystack);
      bytes memory needle = bytes(_needle);

      if (haystack.length == 0 && needle.length == 0) {
        return 0;
      }

      for (uint i = 0; i < haystack.length; i++) {
        if (i + needle.length > haystack.length) {
          return -1;
        }

        bool found = true;
        for (uint j = 0; j < needle.length; j++) {
          if (haystack[i+j] != needle[j]) {
            found = false;
            break;
          }
        }

        if (found) {
          return int(i);
        }
      }

      return -1;
    }
}