-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; } 
2
  • There's 2 occurrences. bobob - bob bob Commented Nov 13, 2019 at 21:40
  • No, it still returns 1 occurrence. Commented Nov 13, 2019 at 21:48

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.