Counting matching substrings within main string


Question and Examples

Create a function that takes in two strings. Loop over the longer string. Loop over the shorter string. If the characters don't match, break out of the inner loop. If the characters do match, keep going. If you complete the inner loop and find a match, increment the count of matches. Return the count.

// Examples
findSubstring("Hello World", "llo") // 1
findSubstring("Please hire me, please", "please") // 2

My Approach

function findSubstring(str1, str2) {
  const mainString = str1.toLowerCase();
  const subString = str2.toLowerCase();
  let pointer1 = 0
  let pointer2 = 0
  let count = 0;
  for (let i = 0; i <= str2; i++) {
    let letterOfFirstString = mainString[i];
    for (let j = 0; j <= str2; j++) {
      let letterOfSecondString = subString[j];
      if (letterOfFirstString !== letterOfSecondString) {
        return
      }
    }
    count = count + 1
  }
  return count
}

I was somewhat stumped with this question. Although it didn't seem to be difficult in my head, it surely was :/

A Better Approah

function searchSubString(string, subString) {
  let counter = 0
  // loop over first string
  for(let i = 0; i < string.length; i++) {
    // loop over substring
    for(let j = 0; j < subString.length; j++) {
      // while comparing, if two letters don't match
      // break the loop
      if(subString[j] !== string[i + j]) {
        break
      }
      // if value of j reaches the end of the substring
      // increment the counter by 1
      if(j === subString.length - 1) {
        counter++
      }
    }
  }
  return counter
}

It turned out that I was overcomplicating things in my code. I didn't have to implement pointers or anything. All I needed to do was loop over a loop and check whether the letters matched or not. If they didn't match, break out of the loop.


Go back to list