1.8 KiB
1.8 KiB
id, title, challengeType, forumTopicId, dashedName
id | title | challengeType | forumTopicId | dashedName |
---|---|---|---|---|
596fda99c69f779975a1b67d | Contare le occorrenze di una sottostringa | 5 | 302237 | count-occurrences-of-a-substring |
--description--
Crea una funzione, o mostra una funzione integrata, per contare il numero di occorrenze non sovrapposte di una sottostringa all'interno di una stringa.
La funzione dovrebbe prendere due argomenti:
- il primo argomento è la stringa da esaminare, e
- il secondo la sotto-stringa da trovare.
Dovrebbe restituire un numero intero.
La ricerca dovrebbe produrre il maggior numero di sottostringhe non sovrapposte.
In generale, questo significa essenzialmente cercare da sinistra a destra o da destra a sinistra.
--hints--
countSubstring
dovrebbe essere una funzione.
assert(typeof countSubstring === 'function');
countSubstring("the three truths", "th")
dovrebbe restituire 3
.
assert.equal(countSubstring(testCases[0], searchString[0]), results[0]);
countSubstring("ababababab", "abab")
dovrebbe restituire 2
.
assert.equal(countSubstring(testCases[1], searchString[1]), results[1]);
countSubstring("abaabba*bbaba*bbab", "a*b")
dovrebbe restituire 2
.
assert.equal(countSubstring(testCases[2], searchString[2]), results[2]);
--seed--
--after-user-code--
const testCases = ['the three truths', 'ababababab', 'abaabba*bbaba*bbab'];
const searchString = ['th', 'abab', 'a*b'];
const results = [3, 2, 2];
--seed-contents--
function countSubstring(str, subStr) {
return true;
}
--solutions--
function countSubstring(str, subStr) {
const escapedSubStr = subStr.replace(/[.+*?^$[\]{}()|/]/g, '\\$&');
const matches = str.match(new RegExp(escapedSubStr, 'g'));
return matches ? matches.length : 0;
}