Files
freeCodeCamp/curriculum/challenges/chinese/10-coding-interview-prep/rosetta-code/count-occurrences-of-a-substring.md
Oliver Eyton-Williams ee1e8abd87 feat(curriculum): restore seed + solution to Chinese (#40683)
* feat(tools): add seed/solution restore script

* chore(curriculum): remove empty sections' markers

* chore(curriculum): add seed + solution to Chinese

* chore: remove old formatter

* fix: update getChallenges

parse translated challenges separately, without reference to the source

* chore(curriculum): add dashedName to English

* chore(curriculum): add dashedName to Chinese

* refactor: remove unused challenge property 'name'

* fix: relax dashedName requirement

* fix: stray tag

Remove stray `pre` tag from challenge file.

Signed-off-by: nhcarrigan <nhcarrigan@gmail.com>

Co-authored-by: nhcarrigan <nhcarrigan@gmail.com>
2021-01-12 19:31:00 -07:00

79 lines
1.6 KiB
Markdown

---
id: 596fda99c69f779975a1b67d
title: 计算子字符串的出现次数
challengeType: 5
videoUrl: ''
dashedName: count-occurrences-of-a-substring
---
# --description--
任务:
创建函数或显示内置函数,以计算字符串中子字符串的非重叠出现次数。
该函数应该有两个参数:
第一个参数是要搜索的字符串,第二个参数是要搜索的子字符串。
它应该返回一个整数计数。
匹配应产生最多数量的非重叠匹配。
通常,这实质上意味着从左到右或从右到左匹配。
# --hints--
`countSubstring`是一个函数。
```js
assert(typeof countSubstring === 'function');
```
`countSubstring("the three truths", "th")`应该返回`3`
```js
assert.equal(countSubstring(testCases[0], searchString[0]), results[0]);
```
`countSubstring("ababababab", "abab")`应返回`2`
```js
assert.equal(countSubstring(testCases[1], searchString[1]), results[1]);
```
`countSubstring("abaabba*bbaba*bbab", "a*b")`应返回`2`
```js
assert.equal(countSubstring(testCases[2], searchString[2]), results[2]);
```
# --seed--
## --after-user-code--
```js
const testCases = ['the three truths', 'ababababab', 'abaabba*bbaba*bbab'];
const searchString = ['th', 'abab', 'a*b'];
const results = [3, 2, 2];
```
## --seed-contents--
```js
function countSubstring(str, subStr) {
return true;
}
```
# --solutions--
```js
function countSubstring(str, subStr) {
const escapedSubStr = subStr.replace(/[.+*?^$[\]{}()|/]/g, '\\$&');
const matches = str.match(new RegExp(escapedSubStr, 'g'));
return matches ? matches.length : 0;
}
```