我怎样才能计算一个特定的字符串在另一个字符串中出现的次数。例如,这是我在Javascript中试图做的事情。
var temp = "This is a string.";
alert(temp.count("is")); //should output '2'
正则表达式中的 "g"(global的缩写)表示要搜索整个字符串,而不是只找第一次出现的。这与 "is "匹配两次。
var temp = "这是一个字符串."。
var count = (temp.match(/is/g) || []).length;
console.log(count)。
var temp = "Hello World!";
var count = (temp.match(/is/g) || []).length;
console.log(count)。
var theString = "This is a string.";
console.log(theString.split("is").length - 1);
<!--结束片段-->
非regex版本:。
<!--开始片段。 js hide: false console: true babel.false --> -- begin snippet: js hide: false console: true false -->
var string = 'This is a string',
searchFor = 'is',
count = 0,
pos = string.indexOf(searchFor);
while (pos > -1) {
++count;
pos = string.indexOf(searchFor, ++pos);
}
console.log(count); // 2
<!--结束片段-->
只是在打码-高尔夫Rebecca Chernoff'的解决方案 :-)
alert(("This is a string.".match(/is/g) || []).length);
<!--开始片段。 js hide: false console: true babel.false --> -- begin snippet: js hide: false console: true false -->
String.prototype.Count = function (find) {
return this.split(find).length - 1;
}
console.log("This is a string.".Count("is"));
<!--结束片段-->。
这将返回2。
这里是最快的功能!
为什么会快?
String.prototype.timesCharExist=function(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名和1个var的误用。
要使用它,你只需这样做。
'The char "a" only shows up twice'.timesCharExist('a');
编辑。 (2013/12/16)
不要与Opera 12.16或更老的版本一起使用!它将花费比regex解决方案多近2.5倍的时间。 它将需要比regex解决方案多2.5倍的时间!在chrome上,这个解决方案将需要14ms到20ms的时间来处理1,000,000个字符。
在chrome上,这个解决方案将需要14ms到20ms的时间来处理1,000,000个字符。
同样数量的字符,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');
所有解法的结果应该是10万!
如果你想让这个函数计算多于1个字符,请将其中的c=(c+'')[0]
改为c=c+''
。
我认为regex的目的与indexOf
有很大不同。
indexOf
只是查找某个字符串的出现,而在regex中,你可以使用通配符,如[A-Z]
,这意味着它将查找单词中的**个大写字母,而无需说明实际的字符。
例如:<!
<!--开始片段。 js hide: false console: true babel.false --> -- begin snippet: js hide: false console: true false -->
var index = "This is a string".indexOf("is");
console.log(index);
var length = "This is a string".match(/[a-z]/g).length;
// where [a-z] is a regex wildcard expression thats why its slower
console.log(length);
<!--结束片段-->
对于将来发现这条线的人来说,请注意,如果你把它泛化,接受的答案并不总是返回正确的值,因为它将扼杀像$
和.
这样的regex运算符。
这里有一个更好的版本,它可以处理任何针。
function occurrences (haystack, needle) {
var _needle = needle
.replace(/\[/g, '\\[')
.replace(/\]/g, '\\]')
return (
haystack.match(new RegExp('[' + _needle + ']', 'g')) || []
).length
}
超级超级老,但我今天需要做这样的事情,事后才想到去查SO。 对我来说挺快的。
String.prototype.count = function(substr,start,overlap) {
overlap = overlap || false;
start = start || 0;
var count = 0,
offset = overlap ? 1 : substr.length;
while((start = this.indexOf(substr, start) + offset) !== (offset - 1))
++count;
return count;
};
var myString = "This is a string.";
var foundAtPosition = 0;
var Count = 0;
while (foundAtPosition != -1)
{
foundAtPosition = myString.indexOf("is",foundAtPosition);
if (foundAtPosition != -1)
{
Count++;
foundAtPosition++;
}
}
document.write("There are " + Count + " occurrences of the word IS");
请参考:-计算字符串中出现的子串的步骤解释。
在上面@Vittim.us回答的基础上。 我喜欢他的方法给我的控制,使其易于扩展,但我需要添加大小写不敏感,并限制匹配到整个单词,支持标点符号。 (例如 "bath" 是在"洗澡." 但不是"bathing")。)
标点符号重词来自。 https://stackoverflow.com/a/25575009/497745 (https://stackoverflow.com/questions/4328500/how-can-i-strip-all-punctuation-from-a-string-in-javascript-using-regex)
function keywordOccurrences(string, subString, allowOverlapping, caseInsensitive, wholeWord)
{
string += "";
subString += "";
if (subString.length <= 0) return (string.length + 1); //deal with empty strings
if(caseInsensitive)
{
string = string.toLowerCase();
subString = subString.toLowerCase();
}
var n = 0,
pos = 0,
step = allowOverlapping ? 1 : subString.length,
stringLength = string.length,
subStringLength = subString.length;
while (true)
{
pos = string.indexOf(subString, pos);
if (pos >= 0)
{
var matchPos = pos;
pos += step; //slide forward the position pointer no matter what
if(wholeWord) //only whole word matches are desired
{
if(matchPos > 0) //if the string is not at the very beginning we need to check if the previous character is whitespace
{
if(!/[\s\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&\(\)*+,\-.\/:;<=>?@\[\]^_`{|}~]/.test(string[matchPos - 1])) //ignore punctuation
{
continue; //then this is not a match
}
}
var matchEnd = matchPos + subStringLength;
if(matchEnd < stringLength - 1)
{
if (!/[\s\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&\(\)*+,\-.\/:;<=>?@\[\]^_`{|}~]/.test(string[matchEnd])) //ignore punctuation
{
continue; //then this is not a match
}
}
}
++n;
} else break;
}
return n;
}
如果你发现BUG或改进,请自由修改和重构这个答案。
<!--开始片段。 js hide: false console: true babel.false --> -- begin snippet: js hide: false console: true false -->
function get_occurrence(varS,string){//Find All Occurrences
c=(string.split(varS).length - 1);
return c;
}
temp="This is a string.";
console.log("Total Occurrence is "+get_occurrence("is",temp));
<!--结束片段-->
使用get_occurrence(varS,string)来查找字符串中字符和字符串的出现次数。