Detect a substring in a string

chandrapenugonda

chandra penugonda

Posted on August 12, 2023

Detect a substring in a string

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

Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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"));

Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
chandrapenugonda
chandra penugonda

Posted on August 12, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Detect a substring in a string
javascript Detect a substring in a string

August 12, 2023