Submission 0f2ab403...

ChallengeString search
Submittermakoto.gitcoin.eth
Submitted at2018-07-03
Gas used327342
/**
 * 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 h = bytes(haystack);
      bytes memory n = bytes(needle);
      uint nl = n.length;
      uint hl = h.length;
      if(nl ==  0 ) return 0;
      if(nl >  hl) return -1;
      for (uint i = 0; i < hl - nl + 1; i++){
          if(h[i] == n[0]){
             for(uint j = 0; j < nl; j++){
                if(h[j+i] != n[j]){
                    i=i+j;
                    break;
                }
             }
            if(j == nl){
               return int(i);
            }
          }
      }
      return -1;
    }
}