检查给定字符串中String的重复

时间:2014-11-24 16:34:18

标签: javascript

我搜索了标题并找到了一些解决方案,但它们都没有为我工作。我想要以下内容:

checkRepeat('ccc','cc');  // should give output 2
checkRepeat('cccaacddcccc','cc');  // should give output 5

等等。请帮我解决一下这个。

我尝试了什么:

function checkRepeat(string, search) {
    if (!search.length) return 0;
    var pattern = new RegExp('(' + search + ')', 'ig'),
        match = string.match(pattern),
        parts = string.split(pattern).slice().filter(function (i) {
            return i.length;
        });
    console.log(match.length);
    console.log(parts.length - 1);
}

3 个答案:

答案 0 :(得分:2)

递归可以满足您的需求:

// from http://stackoverflow.com/a/646643/1225328
function startWith(str, sub) {
    return str.slice(0, sub.length) === sub;
}

function checkRepeat(str, sub) {
    // stop recursion when "str" or "sub" is empty
    if (!sub.length || !str.length) {
        return 0;
    }
    // recursion on "str" minus its first char
    return (startWith(str, sub) ? 1 : 0) + checkRepeat(str.slice(1), sub);
}

迭代解决方案:

function checkRepeat(str, sub) {
    if (!sub.length) {
        return 0;
    }
    var n = sub.length;
    var count = 0;
    for (var i = 0; i <= str.length - n; i++) {
        if (str.slice(i, i + n) === sub) {
            count++;
        }
    }
    return count;
}

答案 1 :(得分:1)

这应该使用正则表达式:

function checkRepeat(string, search) {
    if (!search.length) return 0; 
    var myRe = new RegExp(search, 'g');
    var count = 0;
    while (myRe.exec(string) !== null) {
        count++;
        myRe.lastIndex -= search.length-1;
    }
    return count;
}
alert(checkRepeat('ccc', 'cc')); // 2
alert(checkRepeat('cccaacddcccc', 'cc')); // 5

JSFiddle

答案 2 :(得分:1)

试试这个:

function checkRepeat(f, s, o) {
    return (f.length && s.length) 
           ? f.match(new RegExp((o || (undefined === o)) ? '(?=(' + s + '))' : f, 'g')).length 
           : 0;
}

此解决方案结合了您的问题以及此comment

checkRepeat('cccaacddcccc','cc');  // output 5
checkRepeat('cccaacddcccc','cc', false);  // output 1, as overlap is set to false