Last active
August 3, 2016 04:43
-
-
Save geraldyeo/6cf09fb2dd586f03a0c04d90caff9c69 to your computer and use it in GitHub Desktop.
Write a function that takes two strings, and returns the index of the first occurrence of one string in the other.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Write a function that takes two strings, and returns the index of the first occurrence of one string in the other | |
// Do not use built-in functions: indexOf, substr, substring, array.split | |
function indexof(strToFind, str) { | |
var len1 = str.length; | |
var len2 = strToFind.length; | |
var i, j, numCorrect; | |
for (i=0; i<len1; i++) { | |
numCorrect = 0; | |
for (j=0; j<len2; j++) { | |
if (str.charAt(i+j) === strToFind.charAt(j)) { | |
numCorrect += 1; | |
} | |
} | |
if (numCorrect === len2) { | |
return i; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment