Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[js] 第7天 统计某一字符或字符串在另一个字符串中出现的次数 #21

Open
haizhilin2013 opened this issue Apr 22, 2019 · 89 comments
Labels
js JavaScript

Comments

@haizhilin2013
Copy link
Collaborator

第7天 统计某一字符或字符串在另一个字符串中出现的次数

@haizhilin2013 haizhilin2013 added the js JavaScript label Apr 22, 2019
@linghucq1
Copy link

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'))

@coderfe
Copy link

coderfe commented May 9, 2019

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;
}

@undefinedYu
Copy link
Contributor

这里找到一个好方法。希望能有用。
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);
}

@qqdnnd
Copy link

qqdnnd commented May 16, 2019

function getStrTimes(str,rule){
    return rule !=='' && str.match(new RegExp(rule,'g'))? str.match(new RegExp(rule,'g')).length : 0;
}

@Shoryukenbt
Copy link

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

@tiyunchen
Copy link

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

感觉没毛病

@myprelude
Copy link

fucntion repeat(str,parentStr){
  return parentStr.split(str).length - 1
}

@AricZhu
Copy link

AricZhu commented Jun 19, 2019

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

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

}

@bWhirring
Copy link

function count(str, param) {
  const reg = new RegExp(param, 'g');
  return str.match(reg).length;
}

@Konata9
Copy link

Konata9 commented Jul 4, 2019

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));

@poporeki
Copy link

poporeki commented Jul 4, 2019

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

这个好啊 又简单

@15190408121
Copy link

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, "你好")

@taiyangxingchen
Copy link

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

这个真心不错

@shufangyi
Copy link

const countString = (str, chars) => (
  (arr = str.match(new RegExp(chars, 'g'))), arr && chars ? arr.length : 0
)

@pythonqi
Copy link

fucntion repeat(str,parentStr){
  return parentStr.split(str).length - 1
}

function 关键字写错了

@wyx2014
Copy link

wyx2014 commented Jul 24, 2019

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; } }

@Vi-jay
Copy link

Vi-jay commented Jul 25, 2019

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

@wsb260
Copy link

wsb260 commented Jul 31, 2019

// 方法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

@nnnnnnnnnni
Copy link

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

哈哈哈哈和你的想法一样

@J1nvey
Copy link

J1nvey commented Sep 5, 2019

const letter = "a";
const str = "abcaabccabcaa"
const time = (str, letter) => str.split(letter).length - 1;
console.log(time(str, letter)) // 6

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

@JJL-SH
Copy link

JJL-SH commented Sep 5, 2019

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"));

@funlee
Copy link

funlee commented Sep 7, 2019

function count(str, string) {
  return Math.max(0, string.split(str).length - 1);
}

@liaoyf
Copy link

liaoyf commented Sep 17, 2019

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

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

@Daniel-Fang
Copy link

fucntion repeat(str,parentStr){
  return parentStr.split(str).length - 1
}
function fn(str, substr) {
    if(substr === '') return 0;
    return str.split(substr).length - 1;
}

@JYone223
Copy link

const subStrTimes = (str, sub) => {
  return Array.from(str.matchAll(sub), m => m[0]).length;
}

@lijunren
Copy link

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

@username-xu
Copy link

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

console.log(strArr.length -1)

@mopig
Copy link

mopig commented Sep 29, 2019

function counter(str, subStr, num = 0, index = 0) {
	let tempIndex = str.indexOf(subStr, index)
    return tempIndex > -1 ? counter(str, subStr, ++num, ++tempIndex) : num
}

@Penndo
Copy link

Penndo commented Feb 5, 2021

function statistics(str1,str2){
    let reg = new RegExp(`${str1}{1}`,'g');
    return str2.match(reg).length;
}

@VaynePeng
Copy link

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

@lxt-ing
Copy link

lxt-ing commented Apr 14, 2021

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

@378406712
Copy link

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"));

@378406712
Copy link

@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"));

...想复杂了

@TheRest0
Copy link

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

@cielaber
Copy link

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))
}
}

@4479zheng
Copy link

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")

@shellyxiao48
Copy link

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
}

@codeyourwayup
Copy link

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));

@Injured-Double
Copy link

    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

@FoxJokerEila
Copy link

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'));

@xuan-123
Copy link

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

@xuan-123
Copy link

@Shoryukenbt

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

哈哈 我也是这么想的

@amikly
Copy link

amikly commented Oct 25, 2021

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("", ""));

@VaynePeng
Copy link

function strCount(str, char) {
  return str.split(char).length - 1
}

strCount('abcabc', 'abc')

@Rednaxela-2
Copy link

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

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

@github-cxtan
Copy link

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

@QiaoIsMySky
Copy link

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

@sup194
Copy link

sup194 commented Feb 23, 2022

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

@yxllovewq
Copy link

不使用正则:

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;

@storm-cao
Copy link

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

@wenxd
Copy link

wenxd commented May 20, 2022

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')

@xiaoqiangz
Copy link

// 统计某一字符或字符串在另一个字符串中出现的次数
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'))

@xiaoxiaozhiya
Copy link

方法一正则
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 方法不接受负的参数

@www-wanglong
Copy link

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

count('a', 'abcsadfwretaabcerwawabc')

@wyy-g
Copy link

wyy-g commented Sep 8, 2022

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

@mocc124
Copy link

mocc124 commented Dec 4, 2022

function getCount(str, char) {
  let index = str.indexOf(char);
  if (index < 0) return 0;
  return 1 + getCount(str.slice(index + char.length), char);
}

@tcxiao1
Copy link

tcxiao1 commented Aug 10, 2023

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)

双指针

@lili-0923
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
js JavaScript
Projects
None yet
Development

No branches or pull requests