how to build a function that searches for string occurrences?

You can try this logic:

  • Loop over string and count number of occurance
  • if count is 2,
    • Create a regex to capture the string in between.
    • Return its length
  • Else return 0

function subLength(str, char) {
  let length = 0;
  const occuranceCount = Array
    .from(str)
    .filter((c) => c.toLowerCase() === char.toLowerCase())
    .length
  if (occuranceCount === 2) {
    const regex = new RegExp(`${char}(.*)${char}`)
    length = str.match(regex)[0].length
  }
  console.log(length)
  return length;
}

subLength('Saturday', 'a'); // returns 6
subLength('summer', 'm'); // returns 2
subLength('digitize', 'i'); // returns 0
subLength('cheesecake', 'k'); // returns 0

Using just for loop:

function subLength(str, char) {
  let count = 0;
  let initPosition;
  let lastPosition;
  for (let i = 0; i < str.length; i++) {
    if (str[i] === char) {
      count++
      if (count > 2) {
        return 0;
      }
      if (initPosition === undefined) {
        initPosition = i
      } else {
        lastPosition = i+1
      }
    }
  }
  return count < 2 ? 0 : lastPosition - initPosition;
}

console.log(subLength('Saturday', 'a')); // returns 6
console.log(subLength('summer', 'm')); // returns 2
console.log(subLength('digitize', 'i')); // returns 0
console.log(subLength('cheesecake', 'k')); // returns 0

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top