如何计算特定字符串在另一个字符串中出现的次数。例如,这就是我试图在Javascript中做的事情:
var temp = "This is a string.";
alert(temp.count("is")); //should output '2'
如何计算特定字符串在另一个字符串中出现的次数。例如,这就是我试图在Javascript中做的事情:
var temp = "This is a string.";
alert(temp.count("is")); //should output '2'
当前回答
您可以使用match来定义这样的函数:
String.prototype.count = function(search) {
var m = this.match(new RegExp(search.toString().replace(/(?=[.\\+*?[^\]$(){}\|])/g, "\\"), "g"));
return m ? m.length:0;
}
其他回答
这是最快的功能!
为什么速度更快?
不逐个字符检查(有1个例外)使用while并增加1个var(字符计数var),而不是for循环检查长度并增加2个var(通常是var i和一个带有字符计数的var)使用WAY less vars不使用正则表达式!使用(希望)高度优化的函数所有操作都尽可能地组合在一起,避免了由于多次操作而导致的速度减慢String.product.timesCharExist=函数(c){var t=0,l=0,c=(c+“”)[0];while(l=this.indexOf(c,l)+1)++t;return t};
以下是一个更慢、更可读的版本:
String.prototype.timesCharExist = function ( chr ) {
var total = 0, last_location = 0, single_char = ( chr + '' )[0];
while( last_location = this.indexOf( single_char, last_location ) + 1 )
{
total = total + 1;
}
return total;
};
由于计数器、长的var名称和对1var的误用,这个速度较慢。
要使用它,只需执行以下操作:
'The char "a" only shows up twice'.timesCharExist('a');
编辑:(2013/12/16)
不要与Opera 12.16或更高版本一起使用!它将比正则表达式解决方案花费几乎2.5倍的时间!
在chrome上,对于1000000个字符,此解决方案需要14ms到20ms。
相同量的regex溶液需要11-14ms。
使用函数(String.prototype外部)大约需要10-13ms。
以下是使用的代码:
String.prototype.timesCharExist=function(c){var t=0,l=0,c=(c+'')[0];while(l=this.indexOf(c,l)+1)++t;return t};
var x=Array(100001).join('1234567890');
console.time('proto');x.timesCharExist('1');console.timeEnd('proto');
console.time('regex');x.match(/1/g).length;console.timeEnd('regex');
var timesCharExist=function(x,c){var t=0,l=0,c=(c+'')[0];while(l=x.indexOf(c,l)+1)++t;return t;};
console.time('func');timesCharExist(x,'1');console.timeEnd('func');
所有解决方案的结果应该是100000!
注意:如果您希望此函数计数超过1个字符,请将其中的c=(c+“”)[0]更改为c=c+“”
一种简单的方法是将字符串拆分为所需单词,即我们要计算出现次数的单词,然后从部分数中减去1:
function checkOccurences(string, word) {
return string.split(word).length - 1;
}
const text="Let us see. see above, see below, see forward, see backward, see left, see right until we will be right";
const count=countOccurences(text,"see "); // 2
var mystring = 'This is the lorel ipsum text';
var mycharArray = mystring.split('');
var opArr = [];
for(let i=0;i<mycharArray.length;i++){
if(mycharArray[i]=='i'){//match the character you want to match
opArr.push(i);
}}
console.log(opArr); // it will return matching index position
console.log(opArr.length); // it will return length
你可以试试这个
let count = s.length - s.replace(/is/g, "").length;
此函数在三种模式下工作:查找字符串中单个字符的频率,查找字符串中相邻子字符串的频率,然后如果它与一个匹配,则会直接向前移动到它后面的下一个,第三个与前一个相似,但它也会计算给定字符串中的交叉子字符串
函数substringFrequency(字符串、子字符串、连接){let索引允许发生频率=0for(设i=0;i<string.length;i++){index=string.indexOf(substring,i)如果(索引!=-1){if((子字符串长度==1)||连接==true){i=索引}其他{i=索引+1}发生频率++}其他{打破} }return(发生频率)}console.log(substringFrequency('vvv','v'))console.log(substringFrequency('vvv','vv'))console.log(substringFrequency('vvv','vv'))