GithubHelp home page GithubHelp logo

Comments (89)

Shoryukenbt avatar Shoryukenbt commented on May 4, 2024 220

var childInNums = parent.split(child).length - 1, 这个没毛病吧

from fe-interview.

undefinedYu avatar undefinedYu commented on May 4, 2024 21

这里找到一个好方法。希望能有用。
function substrCount(str, target) {
if(Object.prototype.toString.call(str).slice(8,-1) === 'String' && !str)
alert("请填写字符串");
else
return (str.match(new RegExp(target, 'g')).length);
}

from fe-interview.

linghucq1 avatar linghucq1 commented on May 4, 2024 15
function strCount(str, target) {
  let count = 0
  if (!target) return count
  while(str.match(target)) {
    str = str.replace(target, '')
    count++
  }
  return count
}

console.log(strCount('abcdef abcdef a', 'abc'))

from fe-interview.

myprelude avatar myprelude commented on May 4, 2024 12
fucntion repeat(str,parentStr){
  return parentStr.split(str).length - 1
}

from fe-interview.

liaoyf avatar liaoyf commented on May 4, 2024 10

‘’aa‘’在“aaabcaaa”中出现几次?如果是两次上述答案没有问题,如果是四次
应该可以用零宽正向断言

function subCount(str,target){
  let matchs = str.match(new RegExp(`(?=${target})`, 'g'))
  return matchs ? matchs.length : 0
}

from fe-interview.

Konata9 avatar Konata9 commented on May 4, 2024 4
const countAppears = (str, target) => {
  let count = 0;

  if (!str || !target) {
    return count;
  }

  const keyIndex = target.indexOf(str);
  if (keyIndex > -1) {
    count = 1 + countAppears(str, target.slice(keyIndex + 1));
  }

  return count;
};

const str = "abcaaadefg2333333333334abcddddea";

console.log(countAppears("2", str));
console.log(countAppears("b", str));
console.log(countAppears("d", str));
console.log(countAppears("a", str));
console.log(countAppears("f", str));

from fe-interview.

nikolausliu avatar nikolausliu commented on May 4, 2024 4
const countSub = (str, sub) => str.split(sub).length - 1

from fe-interview.

zlqGitHub avatar zlqGitHub commented on May 4, 2024 4

看了上面大家写的几种,有些多少会存在问题,没有将所有的情景考考进去。
我们应该只能将匹配到的字符第一个字符去掉,他的其他字符依旧可以参与运算中去

      function strCount(str, target) {
            var count = 0;
            if(!target) return count;
            while(str.match(target)) {
                count++;
                // 注意:一定要将当前匹配到的字符第一位及之前的的删除掉
                str = str.substr(str.indexOf(target)+1);

                // 这样处理有缺陷,没有将所有的情况考虑周全
                // str = str.replace(target, '');   
            } 
            return count;
        }
        console.log(strCount('abcdef abcdef a', 'abc'));   //2
        console.log(strCount('ababacdaba', 'aba'));   //3

image

from fe-interview.

coderfe avatar coderfe commented on May 4, 2024 3
function substrCount(str, target) {
  let count = 0;
  while (str.includes(target)) {
    const index = str.indexOf(target);
    count++;
    str = str.substring(index + target.length);
  }
  return count;
}

from fe-interview.

tiyunchen avatar tiyunchen commented on May 4, 2024 3

var childInNums = parent.split(child).length - 1, 这个没毛病吧

感觉没毛病

from fe-interview.

poporeki avatar poporeki commented on May 4, 2024 2

var childInNums = parent.split(child).length - 1, 这个没毛病吧

这个好啊 又简单

from fe-interview.

taiyangxingchen avatar taiyangxingchen commented on May 4, 2024 2

var childInNums = parent.split(child).length - 1, 这个没毛病吧

这个真心不错

from fe-interview.

shufangyi avatar shufangyi commented on May 4, 2024 2
const countString = (str, chars) => (
  (arr = str.match(new RegExp(chars, 'g'))), arr && chars ? arr.length : 0
)

from fe-interview.

0x3c avatar 0x3c commented on May 4, 2024 2
/**
 * @param {string} str
 * @param {string} target
 * @return {number}
 */
function count(str, target) {
  var n = 0,
    index = -1;
  while (index) {
    index = str.indexOf(target, index) + 1;
    index && n++;
  }
  return n;
}

from fe-interview.

gaoryrt avatar gaoryrt commented on May 4, 2024 2

最高票用 split 的错了!

请思考一下,ababa 里面出现 aba 的次数是多少?
再思考一下,'ababa'.split('aba').length - 1 是多少?

楼上去年就说过这个问题了:#21 (comment)

我五月份也回了个贴就在上面:#21 (comment)

楼上还在「确实牛逼」呢……
单元测试用例多想几个,或者是看看回复都不会出现这种问题

from fe-interview.

bWhirring avatar bWhirring commented on May 4, 2024 1
function count(str, param) {
  const reg = new RegExp(param, 'g');
  return str.match(reg).length;
}

from fe-interview.

JYone223 avatar JYone223 commented on May 4, 2024 1
const subStrTimes = (str, sub) => {
  return Array.from(str.matchAll(sub), m => m[0]).length;
}

from fe-interview.

qq814927478 avatar qq814927478 commented on May 4, 2024 1
function fun(str, str1) {
	let count = 0;
	for (let item of str) {
		if (item == str1) {
			count++
		}
	}
	return count;
}
console.log(fun('1asds1a1dasdq11wenkjz1xhj1kchgqsj1rge1', '1'))

from fe-interview.

gaoryrt avatar gaoryrt commented on May 4, 2024 1

不是,楼上各位想用 split 实现的,我就问一句

aaaa 中 aa 出现的次数是不是3

from fe-interview.

17325432843 avatar 17325432843 commented on May 4, 2024 1

var parent = 'abababab'
function num(child){
return parent.split(child).length-1
}
console.log(num('a'))

from fe-interview.

qqdnnd avatar qqdnnd commented on May 4, 2024
function getStrTimes(str,rule){
    return rule !=='' && str.match(new RegExp(rule,'g'))? str.match(new RegExp(rule,'g')).length : 0;
}

from fe-interview.

AricZhu avatar AricZhu commented on May 4, 2024

// 递归,一行代码实现
function strRepeatCount (subStr, str, count=0) {

return str.indexOf(subStr) !== -1? strRepeatCount(subStr, str.substring(str.indexOf(subStr)+subStr.length), ++count): count;

}

from fe-interview.

15190408121 avatar 15190408121 commented on May 4, 2024

function strFind (str, target) {
var lengths = 0
if (!target) {
return lengths
}
while(str.match(target)) {
str = str.replace(target, '')
lengths++
}
return lengths
}
var str = "你好 萨达所大所多所多所问问二位无 你好 萨达所大所多 你好"
strFind(str, "你好")

from fe-interview.

pythonqi avatar pythonqi commented on May 4, 2024
fucntion repeat(str,parentStr){
  return parentStr.split(str).length - 1
}

function 关键字写错了

from fe-interview.

wyx2014 avatar wyx2014 commented on May 4, 2024

function getCount1(str, target,count = 0 ) { var index = str.indexOf(target); if(index!== -1){ return getCount1(str.substring(index+target.length),target,++count) }else { return count; } }

from fe-interview.

Vi-jay avatar Vi-jay commented on May 4, 2024
function getTargetCount(arr, target) {
  return arr
    .reduce((group, v) => group.set(v, (group.get(v) || 0) + 1), new Map())
    .get(target);
}
console.log(getTargetCount([1,1,2,5],1));// 2

from fe-interview.

wsb260 avatar wsb260 commented on May 4, 2024

// 方法1

var str = 'aabbcaacddaabbccdd'
var str2 = 'aa'

const contSvg = (s1,s2) => {
  var arr = [];
  arr = s1.split(s2);
  console.log(arr.length-1);
}

contSvg(str,str2) // 输出3

// 方法2

// eval() 函数可计算某个字符串,并执行其中的的 JavaScript 代码。
const strCount = (str, target) => {
  if (!target) return count
	 return  str.match(eval("/"+target+"/g")).length
}

console.log(strCount('abcd abcde a', 'abc')) // 输出2

from fe-interview.

nnnnnnnnnni avatar nnnnnnnnnni commented on May 4, 2024

var childInNums = parent.split(child).length - 1, 这个没毛病吧

哈哈哈哈和你的想法一样

from fe-interview.

J1nvey avatar J1nvey commented on May 4, 2024
const letter = "a";
const str = "abcaabccabcaa"
const time = (str, letter) => str.split(letter).length - 1;
console.log(time(str, letter)) // 6

不知道会不会有没有其他特殊情况,这样写的话。。。

from fe-interview.

JJL-SH avatar JJL-SH commented on May 4, 2024
function strCount(str, target) {
  let count = 0;
  while (str.includes(target)) {
    str = str.replace(target, "");
    count++;
  }
  return count;
}
function strCount(str, target) {
  return str.split(target).length - 1;
}
console.log(strCount("asdgqwidugasgdakisdggfjwdagasd", "gas"));

from fe-interview.

funlee avatar funlee commented on May 4, 2024
function count(str, string) {
  return Math.max(0, string.split(str).length - 1);
}

from fe-interview.

Daniel-Fang avatar Daniel-Fang commented on May 4, 2024
fucntion repeat(str,parentStr){
  return parentStr.split(str).length - 1
}
function fn(str, substr) {
    if(substr === '') return 0;
    return str.split(substr).length - 1;
}

from fe-interview.

lijunren avatar lijunren commented on May 4, 2024

function getTimes(str1, str2) {
if (str2.indexOf(str1) === -1) {
return 0;
}
const arr = str2.splite(str1);
return arr.length - 1;
}

from fe-interview.

username-xu avatar username-xu commented on May 4, 2024

var str = 'aabbccabcaabbccabcabc15114816181abc64641414tregfagfczfavacabaaabc6486';
var strArr = str.split('abc')

console.log(strArr.length -1)

from fe-interview.

mopig avatar mopig commented on May 4, 2024
function counter(str, subStr, num = 0, index = 0) {
	let tempIndex = str.indexOf(subStr, index)
    return tempIndex > -1 ? counter(str, subStr, ++num, ++tempIndex) : num
}

from fe-interview.

censek avatar censek commented on May 4, 2024

var childInNums = parent.split(child).length - 1, 这个没毛病吧

👍

from fe-interview.

wezzzyang avatar wezzzyang commented on May 4, 2024

function a(x,y) { x = x.split(${y}); return x.length - 1 }
a('124awf125awf12awf5','awf')

//'124125125'

from fe-interview.

ducky-YFH avatar ducky-YFH commented on May 4, 2024
function check(checkStr, str, len) {
  if(typeof str !== 'string'){
    return;
  }
  len = len || 0;
  let index = str.indexOf(checkStr);
  if (index !== -1) {
    len += 1;
    str = str.replace(checkStr, '');
    check(checkStr, str, len);
  } else {
    console.log(len);
    return;
  }
}
check('火狐', '火狐、谷歌、ie、360、火狐100')

from fe-interview.

diandianzd avatar diandianzd commented on May 4, 2024
function checkTimes(str, target) {
  return str.split(target).length - 1
}


console.log(checkTimes('abcabde', 'ab'))


function subCount(str,target){
  let matchs = str.match(new RegExp(`(?=${target})`, 'g'))
  return matchs ? matchs.length : 0
}

console.log(subCount('abcabde', 'ab'))

from fe-interview.

crazyming9528 avatar crazyming9528 commented on May 4, 2024
function strCount(origin, str) {
    var reg = new RegExp(str, 'g');
   // console.log(origin.match(reg));
    return origin.match(reg).length;
}


function strCount2(origin, str) {
    return origin.split(str).length - 1;
}

from fe-interview.

yyz841875845 avatar yyz841875845 commented on May 4, 2024

function count1 (str1, str2){
let arr = str2.split(str1)
return arr.length -1
}
count1('aa', 'aababacaaac')

from fe-interview.

YeChang avatar YeChang commented on May 4, 2024
//第7天 统计某一字符或字符串在另一个字符串中出现的次数

function subStrCount(str, sub) {
  var count = 0;
  while (str.includes(sub)) {
    const index = str.indexOf(sub);
    count++;
    str = str.substring(index + sub.length);
  }
  return count;
}
var str = "hello hello hello hello";
console.log(subStrCount(str, "e"));

from fe-interview.

rni-l avatar rni-l commented on May 4, 2024
function getTotal(str, target) {
  const targetLen = target.length
  const targetArray = str.split('')
  return targetArray.reduce((acc, cur, curIndex) => {
    let temp = ''
    for (let i = 0; i <= targetLen - 1; i++) {
      temp += targetArray[i + curIndex]
    }
    if (temp === target) {
      return ++acc
    }
    return acc;
  }, 0)
}
getTotal('hahahahsfdsfdfsda','ha') // 3

from fe-interview.

zcCodeWarehouse avatar zcCodeWarehouse commented on May 4, 2024
function stringStatistics(str,target,num){
  let count=num?num:0
  const index= target.indexOf(str)
  if(index<0) return count
  count++
  target=target.slice(index+str.length)   //这里也可以用空格替换字符串  我用的是直接删掉了前面的字符串
  return stringStatistics(str,target,count)
} 

from fe-interview.

FJY111 avatar FJY111 commented on May 4, 2024
function searchStr (str, word) {
  if (!str.includes(word)) return 0
  let reg = new RegExp(`(?=${word})`, 'g')
  return str.match(reg).length
}

from fe-interview.

blueRoach avatar blueRoach commented on May 4, 2024
function repeatCount(target, code){
  if(typeof target != 'string' || typeof code != 'string'){
    return
  }
  let index = 0, regexp = new RegExp(code, 'g')
  target.replace(regexp, (a) => index++)
  return index
}

大佬的这个确实牛逼
parent.split(child).length - 1

from fe-interview.

1415333545 avatar 1415333545 commented on May 4, 2024

好多正则得也有问题呢

from fe-interview.

giggleCYT avatar giggleCYT commented on May 4, 2024
        function fn(str, tag) {
            var num = 0;
            var reg = new RegExp(tag);
            while (reg.test(str)) {
                str = str.replace(reg, '')
                num++;
            }
            return num;
        }

from fe-interview.

gaoryrt avatar gaoryrt commented on May 4, 2024
        function fn(str, tag) {
            var num = 0;
            var reg = new RegExp(tag);
            while (reg.test(str)) {
                str = str.replace(reg, '')
                num++;
            }
            return num;
        }

fn('ababa', 'aba') // 1
should be 2

from fe-interview.

Fengzhen8023 avatar Fengzhen8023 commented on May 4, 2024

function strShowCount(sourceStr, targetStr) {
let reg = RegExp(targetStr, "g");
let timer = 0;
while(reg.exec(sourceStr)) {
timer++;
}
return timer;
}

console.log(strShowCount("AllenFengeeeeeeFengALlenFen", "Feng"));

from fe-interview.

LancelotSaki avatar LancelotSaki commented on May 4, 2024

这题出得不太严谨吧,若考虑到里面的字符被复用,那得出的结果不是不一样了。

from fe-interview.

Alex-Li2018 avatar Alex-Li2018 commented on May 4, 2024

'abc abce fghabc abc'.match(/abc/g)

from fe-interview.

hou499 avatar hou499 commented on May 4, 2024

整理了一下前面正确的方法

function searchStr(str, target) {
    if (!target || !str.includes(target)) return 0;
    let reg = new RegExp(`(?=${target})`, 'g');
    return str.match(reg).length;
}
function strCount(str, target) {
    var count = 0;
    if (!target) return count;
    while (str.match(target)) {
        count++;
        str = str.substr(str.indexOf(target) + 1);
    }
    return count;
}
function count(str, target) {
    var n = 0,
        index = -1;
    while (index) {
        index = str.indexOf(target, index) + 1;
        index && n++;
    }
    return n;
}
function counter(str, subStr, num = 0, index = 0) {
    let tempIndex = str.indexOf(subStr, index);
    return tempIndex > -1 ? counter(str, subStr, ++num, ++tempIndex) : num;
}
function getTotal(str, target) {
    const targetLen = target.length;
    const targetArray = str.split('');
    return targetArray.reduce((acc, cur, curIndex) => {
        let temp = '';
        for (let i = 0; i <= targetLen - 1; i++) {
            temp += targetArray[i + curIndex];
        }
        if (temp === target) {
            return ++acc;
        }
        return acc;
    }, 0);
}

from fe-interview.

laboonly avatar laboonly commented on May 4, 2024

function somestr (str, target) {

let length = str.length;
let count = target.length;
let sum = 0;
for(let i = 0; i < length - count; i++) {
    if(str.slice(i,i + count) == target) {
        sum++
    }
}
return sum;

}

let sum = somestr('aabbccdbbcdebbceff', 'c');

from fe-interview.

yangyingwx avatar yangyingwx commented on May 4, 2024
let i = 0
let reg = /abc/g
while(reg.test(str)){
  ++i
}
console.log(i)

image

from fe-interview.

ascreamz avatar ascreamz commented on May 4, 2024

function getTotal(str,target){
return str.match(new RegExp(target,'g')).length;
}

from fe-interview.

knwceas avatar knwceas commented on May 4, 2024
function count(str1, str2) {
  let s = 0;
  for (let i = 0; i <= str2.length-str1.length; i++) {
    if (str1 === str2.substring(i, i + str1.length )) s++;
  }  
  return s;
}

from fe-interview.

Liszter avatar Liszter commented on May 4, 2024

function getTargetNum (str, target) {
return str.split(target).length - 1
}

from fe-interview.

17325432843 avatar 17325432843 commented on May 4, 2024

var childInNums = parent.split(child).length - 1, 这个没毛病吧

var childInNums = parent.split(child).length - 1, 这个没毛病吧

想到一起去了

from fe-interview.

Penndo avatar Penndo commented on May 4, 2024
function statistics(str1,str2){
    let reg = new RegExp(`${str1}{1}`,'g');
    return str2.match(reg).length;
}

from fe-interview.

VaynePeng avatar VaynePeng commented on May 4, 2024

function strCount(str, target) { let countArr = str.split(target) return countArr.length - 1 }

from fe-interview.

lxt-ing avatar lxt-ing commented on May 4, 2024

function getSame(str,substr){ let reg = new RegExp(substr,'g'); return str.match(reg).length; }

from fe-interview.

378406712 avatar 378406712 commented on May 4, 2024

let index = 0;
const count = (str, anotherStr) => {
const len = str.length;
if (len === 0) return 0;
else if (len === 1) {
const counts = anotherStr.split("").filter((item) => item === str);
return counts.length;
} else {
const reg = eval(/${str}/);
const tag = anotherStr.search(reg);
if (tag > -1) {
index++;
const newStr = anotherStr.replace(reg, "");
count(str, newStr);
}
return index;
}
};
console.log(count("aaa", "aaabaaabaabaaa"));

from fe-interview.

378406712 avatar 378406712 commented on May 4, 2024

@378406712

let index = 0;
const count = (str, anotherStr) => {
const len = str.length;
if (len === 0) return 0;
else if (len === 1) {
const counts = anotherStr.split("").filter((item) => item === str);
return counts.length;
} else {
const reg = eval(/${str}/);
const tag = anotherStr.search(reg);
if (tag > -1) {
index++;
const newStr = anotherStr.replace(reg, "");
count(str, newStr);
}
return index;
}
};
console.log(count("aaa", "aaabaaabaabaaa"));

...想复杂了

from fe-interview.

TheRest0 avatar TheRest0 commented on May 4, 2024
function strCount(str, target) {
  let arr = str.split(target)
  return arr.length -1
}

from fe-interview.

cielaber avatar cielaber commented on May 4, 2024

let counter = 0;//计数器
function count(str,string){
if(string.length<str.length) return;
if(string.indexOf(str)>-1){
let index = string.indexOf(str)
// console.log(index);
counter++;
count(str,string.slice(index+str.length))
}
}

from fe-interview.

4479zheng avatar 4479zheng commented on May 4, 2024

function frequency(str1,str2){
let num = 0;
let postion = 0;
while(str1.indexOf(str2,postion)!=-1){
postion = str1.indexOf(str2,postion)+1;
str1.indexOf(str2,postion);
num++;
}
console.log(num);
}
frequency("jvkdasjvakj","jv")

from fe-interview.

shellyxiao48 avatar shellyxiao48 commented on May 4, 2024

let num = 0;
function showNum(str, key) {
const len = key.length;
const index = str.indexOf(key)
if (index != -1) {
let newStr = str.substr(0, index) + str.substr(index + len)
num++;
return showNum(newStr, key)
}
return num
}

from fe-interview.

codeyourwayup avatar codeyourwayup commented on May 4, 2024

const countAppears = (char, str) => {

let count = 0;


function run(str) {

    if (!str.includes(char)) {
        return;
    }


    if (str.includes(char)) {
        count++;
        const newStr = str.replace(char, '');

        run(newStr);

    }



}

run(str);

return count;

};

const str = "ab2dx22d";

console.log(countAppears("d", str));
console.log(countAppears("2d", str));
console.log(countAppears("2", str));

from fe-interview.

Injured-Double avatar Injured-Double commented on May 4, 2024
    const str = 'As sly as a fox, as strong as an ox';


    function indexOfNum(obj, target, pos) {

        let count = 0;

        while (true) {
            const index = obj.indexOf(target, pos);

            if (index === -1) break;

            console.log(`Found as at ${index}`);
            pos = index + 1;
            count++;

        }


        return count;

    }


    console.log(indexOfNum(str, 'as', 0)); //3

from fe-interview.

FoxJokerEila avatar FoxJokerEila commented on May 4, 2024

function count(son, mother) {
let c = 0
let arr = []
const first = son[0]
const len = son.length
for (let i = 0; i < mother.length; i++) {
if (mother[i] === first) {
arr.push(i)
}
}
for (item of arr) {
if (son == mother.substring(item, item + len)) {
c++
}
}
return c
}

console.log(count('abc', 'abcdef abcdef a'));

from fe-interview.

xuan-123 avatar xuan-123 commented on May 4, 2024

function toCase(str,target){
return str.split(target).length-1
}

from fe-interview.

xuan-123 avatar xuan-123 commented on May 4, 2024

@Shoryukenbt

var childInNums = parent.split(child).length - 1, 这个没毛病吧

哈哈 我也是这么想的

from fe-interview.

amikly avatar amikly commented on May 4, 2024

split方法

// split 方法
function countStr(str1, str2) {
    return str2.split(str1).length - 1;
}
console.log(countStr("da", "dabshaudaoiddda"));

includes + indexOf + substring 方法

// includes 方法
function countStr(str1, str2) {
    let count = 0;
    while (str1 && str2 && str2.includes(str1)) {
      let index = str2.indexOf(str1);
      count++;
      str2 = str2.substring(index + str1.length);
    }
    return count;
 }
console.log(countStr("da", "dabshaudaoiddda"));

match + replace 方法

// match 方法
function countStr(str1, str2) {
    let count = 0;
    while (str1 && str2 && str2.match(str1)) {
    str2 = str2.replace(str1, "");
    count++;
}
	return count;
}
console.log(countStr(" ", " "));

递归

// 递归
function countStr(str1, str2, count = 0) {
    if (str1 && str2) {
    return str2.indexOf(str1) !== -1
    ? countStr(
    str1,
    str2.substring(str2.indexOf(str1) + str1.length),
    ++count
	)
	: count;
}
	return count;
}
console.log(countStr("da", "dabshaudaoiddda"));
console.log(countStr("", ""));

from fe-interview.

VaynePeng avatar VaynePeng commented on May 4, 2024
function strCount(str, char) {
  return str.split(char).length - 1
}

strCount('abcabc', 'abc')

from fe-interview.

Rednaxela-2 avatar Rednaxela-2 commented on May 4, 2024

var childInNums = parent.split(child).length - 1, 这个没毛病吧

我试了几个方法,这个的速度也是最快的

from fe-interview.

github-cxtan avatar github-cxtan commented on May 4, 2024

function GetCounts(srcData, DetectStr){
let reg = new RegExp(${DetectStr}, 'g');
return srcData.match(reg).length;
}

from fe-interview.

QiaoIsMySky avatar QiaoIsMySky commented on May 4, 2024

let str = 's'
let ostr = 'seowqjoewqskodkwqkdpsadpdkpwq'
let index = 0
ostr.split('').forEach(item => {
if (item === str){
index++
}
})
console.log(index);

from fe-interview.

sup194 avatar sup194 commented on May 4, 2024

function strCount(str, target) {
let count = 0
if (!target) return count
while (str.match(target)) {
str.replact('')
count++
}
return count
}

from fe-interview.

yxllovewq avatar yxllovewq commented on May 4, 2024

不使用正则:

const strCountOf = (str = '', fromStr = '') => {
  let count = 0;
  let start = false;
  let startId;
  for (let i = 0; i < fromStr.length; i++) {
    if (str[0] === fromStr[i]) {
      start = true;
      startId = i;
    }
    if (start) {
      if (str[i - startId] !== fromStr[i]) {
        start = false;
      }
      if (i === startId + str.length - 1) {
        count++;
        start = false;
      }
    }
  }
  return count;
}

使用正则:

const strCountOf = (str = '', fromStr = '') => [...fromStr.matchAll(new RegExp(str, 'g'))].length;

from fe-interview.

storm-cao avatar storm-cao commented on May 4, 2024

const countString = (childStr,parentStr) => parentStr.split(childStr).length - 1);

from fe-interview.

wenxd avatar wenxd commented on May 4, 2024
function statCharInString(str, char) {
    let re = new RegExp(char, 'g')
    let num = str.match(re).length
    console.log(num);
  }
  statCharInString('asf sfas  sadf jjsfahf', 'as')

from fe-interview.

xiaoqiangz avatar xiaoqiangz commented on May 4, 2024

// 统计某一字符或字符串在另一个字符串中出现的次数
function repatCount(str, target) {
// 第一种
// return str.split(target).length - 1
// 第二种
// let count = 0
// while (str.includes(target)) {
// count++
// str = str.replace(target, '')
// }
// return count
// 第三种
let reg = new RegExp(target, 'g')
return str.match(reg).length
}
console.log(repatCount('abcdeaveavffavvfa', 'av'))

from fe-interview.

xiaoxiaozhiya avatar xiaoxiaozhiya commented on May 4, 2024

方法一正则
function getTotalCount(str,target){ var reg=new RegExp(target,"g") var arr=str.match(reg) return arr.length }

方法二
利用字符串的位置关系(间接)
function countStr(str1, str2) { var arr=str2.split(str1) console.log(arr) return str2.split(str1).length - 1; }

方法三
一边判断一边丢

function countStr(str1, str2) { let count = 0; while (str1 && str2 && str2.includes(str1)) { let index = str2.indexOf(str1); count++; str2 = str2.substring(index + str1.length); console.log(str2) } return count; }

  • substring 方法不接受负的参数

from fe-interview.

www-wanglong avatar www-wanglong commented on May 4, 2024

function count(str, target) {
let reg = new RegExp(str, 'g')
return target.match(reg).length
}

count('a', 'abcsadfwretaabcerwawabc')

from fe-interview.

wyy-g avatar wyy-g commented on May 4, 2024

function countStr(str, target){
var count = 0;
while(str.includes(target)){
count++;
str = str.replace(target, '');
}
}

from fe-interview.

mocc124 avatar mocc124 commented on May 4, 2024
function getCount(str, char) {
  let index = str.indexOf(char);
  if (index < 0) return 0;
  return 1 + getCount(str.slice(index + char.length), char);
}

from fe-interview.

tcxiao1 avatar tcxiao1 commented on May 4, 2024

function countStr(target, array, rightIndex, leftIndex, count) {

if (leftIndex > array.length) {
    return count;
}

let source = "";
for (let i = rightIndex; i < leftIndex; i++) {
    source = source + array[i];
}
if (source === target) {
    count++;
}

rightIndex++;
leftIndex++;
return countStr(target, array, rightIndex, leftIndex, count);

}

let target = "aa";
let src = "aaabbcaacddaabbccdd";
let countStr1 = countStr(target, Array.from(src), 0, target.length, 0);
console.log(countStr1)

双指针

from fe-interview.

lili-0923 avatar lili-0923 commented on May 4, 2024

function countStr(str1, str2) {
return str2.split(str1).length - 1;
}

from fe-interview.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.