-1

This is a basic homework problem that I was assigned and I seem to not be understanding how to do it from a logical standpoint. This last problem is to search for a keyword within a string of lowercase characters.

This is the last problem.

  • Problem 2
  • Assume s is a string of lower case characters and a search keyword.
  • Write a program that prints the number of times the search keyword occurs in s.

Example:

  1. Given s = 'azcbobobegghakl' and the search keyword is 'bob'
  2. Your program should print Number of times bob occurs is: 2

I have been able to make the program using a javascript method before to search for a keyword but it only returned 1 occurrence of 'bob'. The problem I am having is the logic to understand how to solve this question. If this was an array of strings or if it was a string with spaces so that the words would be separated then I understand how to do that. But this just confuses me.

This only returns 1 occurrence of 'bob' from string 'azcbobobegghakl' but the professor wants it to return 2 occurrences.

function searchForKeyWord(str, keyword) {
  return str.match(keyword).length;
}
Melchia
  • 22,578
  • 22
  • 103
  • 117

2 Answers2

1

Use an Index to keep Track of ur last Search string Index, if a string gets found increment the counter then Search again in the substring starting at the last found index+searchedword.length if no string ist found return

Sventy
  • 11
  • 1
0

Instead of using using regex you could build your own search function. A simple loop for comparing each occurrence with the keyword:

const s = 'azcbobobegghak';
const search = 'bob';

function searchForKeyWord(str, keyword) {
  if(!keyword || !str) return 0;
  
  let counter = 0;
  const l = keyword.length;
  for( let i = 0 ; i < str.length - l; i++) {
    counter += str.substring(i,i+l) === keyword ? 1 : 0;
  }
  return counter;
}


const output = searchForKeyWord(s,search);
console.log(output);
Melchia
  • 22,578
  • 22
  • 103
  • 117