How would you write a function to detect a substring in a string?
Example
function detectSubstring(string, subString) {
return -1;
}
// console.log(detectSubstring('ggraph', 'graph')); // 1
// console.log(detectSubstring('geography', 'graph')); // 3
// console.log(detectSubstring('digginn', 'inn')); // 4
Solution 1
function detectSubstring(string, subString) {
let j = 0;
for (let i = 0; i < string.length; i++) {
if (string[i] == subString[j]) {
j++;
if (j == subString.length) {
return i - (subString.length - 1);
}
} else {
i -= j;
j = 0;
}
}
return -1;
}
// console.log(detectSubstring('ggraph', 'graph')); // 1
// console.log(detectSubstring('geography', 'graph')); // 3
// console.log(detectSubstring('digginn', 'inn')); // 4
Solution 2
function detectSubstring(string, subString) {
const substringLength = subString.length;
for (let i = 0; i < string.length; i++) {
let j = 0;
while (j < substringLength && string[i + j] === subString[j]) {
j++;
}
if (j === substringLength) {
return i;
}
}
return -1;
}
console.log(detectSubstring("ggraph", "graph"));
console.log(detectSubstring("geography", "graph"));
console.log(detectSubstring("digginn", "inn"));
Top comments (0)