Solution to Rosetta Code Challenge - Count occurrences for a substring

What is your hint or solution suggestion?

function countSubstring(str, subStr) {
    var strarr = str.split('');
    var str1arr = [];
    var index = 0, count = 0;

    while(index < strarr.length){
        var sub = index + subStr.length + 1 <= strarr.length ? strarr.slice(index, index+subStr.length).join('') : strarr.slice(index).join(''); 

/*substring with same number of characters as subStr, check if a substring equals the 
subStr, increment count and remove that substring (non-overlapping occurrences)*/

        if(sub == subStr){
            count++;
            strarr.splice(index, subStr.length);
        }else{
            index++;
        }
    }

    return count;
  }

Challenge: Count occurrences of a substring

Link to the challenge:

// Try this code

const countSubStr = (str, search) => {
    let count = 0;
    let index = str.indexOf(search);
    while(index !== -1){
        count++;
        index = str.indexOf(search , index+1);
    }
    return count;
}

I have added spoiler tags around your code.

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

Hi @abhi.sharma96458 !

Your solution is not passing all of the tests.

What about this modified version of the same logic?

function countSubstring(str, subStr) {
  let i = 0;
  let count = 0;
  const subStrLen = subStr.length;
  const upperBound = str.length - subStrLen;
  while (i < upperBound) {
    if (str.substr(i, subStrLen) == subStr) {
      count++;
      i += subStrLen;
    } else {
      i++;
    }
  }
  return count;
}
1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.