Files
freeCodeCamp/curriculum/challenges/russian/08-coding-interview-prep/rosetta-code/count-occurrences-of-a-substring.russian.md

2.5 KiB
Raw Blame History

title, id, challengeType, forumTopicId, localeTitle
title id challengeType forumTopicId localeTitle
Count occurrences of a substring 596fda99c69f779975a1b67d 5 302237 Количество вхождений подстроки

Description

Задача:

Создайте функцию или покажите встроенную функцию, чтобы подсчитать количество неперекрывающихся вхождений подстроки внутри строки.

Функция должна принимать два аргумента:

первый аргумент - строка для поиска, а вторая - подстрока, которую нужно искать.

Он должен возвращать целочисленное число.

Соответствие должно давать наибольшее количество совпадающих совпадений.

В общем, это по существу означает совмещение слева направо или справа налево.

Instructions

Tests

tests:
  - text: <code>countSubstring</code> is a function.
    testString: assert(typeof countSubstring === 'function');
  - text: <code>countSubstring("the three truths", "th")</code> should return <code>3</code>.
    testString: assert.equal(countSubstring(testCases[0], searchString[0]), results[0]);
  - text: <code>countSubstring("ababababab", "abab")</code> should return <code>2</code>.
    testString: assert.equal(countSubstring(testCases[1], searchString[1]), results[1]);
  - text: <code>countSubstring("abaabba*bbaba*bbab", "a*b")</code> should return <code>2</code>.
    testString: assert.equal(countSubstring(testCases[2], searchString[2]), results[2]);

Challenge Seed

function countSubstring(str, subStr) {
  // Good luck!
  return true;
}

After Tests

const testCases = ['the three truths', 'ababababab', 'abaabba*bbaba*bbab'];
const searchString = ['th', 'abab', 'a*b'];
const results = [3, 2, 2];

Solution

function countSubstring(str, subStr) {
  const escapedSubStr = subStr.replace(/[.+*?^$[\]{}()|/]/g, '\\$&');
  const matches = str.match(new RegExp(escapedSubStr, 'g'));
  return matches ? matches.length : 0;
}