我该如何在一个字符串中统计另一个特定字符串出现的次数?例如,我想在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'
var countInstances = function(body, target) {
var globalcounter = 0;
var concatstring = '';
for(var i=0,j=target.length;i<body.length;i++){
concatstring = body.substring(i-1,j);
if(concatstring === target){
globalcounter += 1;
concatstring = '';
}
}
return globalcounter;
};
console.log( countInstances('abcabc', 'abc') ); // ==> 2
console.log( countInstances('ababa', 'aba') ); // ==> 2
console.log( countInstances('aaabbb', 'ab') ); // ==> 1
这个函数将告诉你子字符串是否在字符串中以及出现了多少次。
const wordInText = (wordToFind, wholeText) => {
const wordToFindRegex = new RegExp(wordToFind, 'gi');
const occurences = wholeText.match(wordToFindRegex) ?? [];
return {isWordInText: occurences.length > 0, occurences: occurences.length};
}
console.log(wordInText("is", "This cow jumped over this moon"))
function subStringCount(ustring, countChar){
var correspCount = 0;
var corresp = false;
var amount = 0;
var prevChar = null;
for(var i=0; i!=ustring.length; i++){
if(ustring.charAt(i) == countChar.charAt(0) && corresp == false){
corresp = true;
correspCount += 1;
if(correspCount == countChar.length){
amount+=1;
corresp = false;
correspCount = 0;
}
prevChar = 1;
}
else if(ustring.charAt(i) == countChar.charAt(prevChar) && corresp == true){
correspCount += 1;
if(correspCount == countChar.length){
amount+=1;
corresp = false;
correspCount = 0;
prevChar = null;
}else{
prevChar += 1 ;
}
}else{
corresp = false;
correspCount = 0;
}
}
return amount;
}
console.log(subStringCount('Hello World, Hello World', 'll'));
var str = 'stackoverflow';
var arr = Array.from(str);
console.log(arr);
for (let a = 0; a <= arr.length; a++) {
var temp = arr[a];
var c = 0;
for (let b = 0; b <= arr.length; b++) {
if (temp === arr[b]) {
c++;
}
}
console.log(`the ${arr[a]} is counted for ${c}`)
}
这个函数有三种模式:在字符串中查找单个字符的频率,查找字符串中的连续子字符串,如果匹配,则继续向右移动到其后面的下一个子字符串,第三种模式与前一种类似,但它还将计算给定字符串中相交的子字符串。
function substringFrequency(string , substring , conjunction){
let index
let occurenceFrequency = 0
for (let i=0 ; i < string.length ; i++){
index = string.indexOf(substring , i)
if (index != -1){
if ((substring.length == 1 ) || conjunction == true) {
i = index
}else {
i = index + 1
}
occurenceFrequency++
}else{
break
}
}
return (occurenceFrequency)
}
console.log(substringFrequency('vvvv' , 'v' ))
console.log(substringFrequency('vvvv' , 'vv'))
console.log(substringFrequency('vvvv' , 'vv' , true))
const getLetterMatchCount = (guessedWord, secretWord) => {
const secretLetters = secretWord.split('');
const guessedLetterSet = new Set(guessedWord);
return secretLetters.filter(letter => guessedLetterSet.has(letter)).length;
};
const str = "rahul";
const str1 = "rajendra";
getLetterMatchCount(str, str1)
substr_count
从php翻译成Javascript
function substr_count (haystack, needle, offset, length) {
// eslint-disable-line camelcase
// discuss at: https://locutus.io/php/substr_count/
// original by: Kevin van Zonneveld (https://kvz.io)
// bugfixed by: Onno Marsman (https://twitter.com/onnomarsman)
// improved by: Brett Zamir (https://brett-zamir.me)
// improved by: Thomas
// example 1: substr_count('Kevin van Zonneveld', 'e')
// returns 1: 3
// example 2: substr_count('Kevin van Zonneveld', 'K', 1)
// returns 2: 0
// example 3: substr_count('Kevin van Zonneveld', 'Z', 0, 10)
// returns 3: false
var cnt = 0
haystack += ''
needle += ''
if (isNaN(offset)) {
offset = 0
}
if (isNaN(length)) {
length = 0
}
if (needle.length === 0) {
return false
}
offset--
while ((offset = haystack.indexOf(needle, offset + 1)) !== -1) {
if (length > 0 && (offset + needle.length) > length) {
return false
}
cnt++
}
return cnt
}
查看 Locutus 对 Php 的 substr_count 函数的翻译
//Try this code
const countSubStr = (str, search) => {
let arrStr = str.split('');
let i = 0, count = 0;
while(i < arrStr.length){
let subStr = i + search.length + 1 <= arrStr.length ?
arrStr.slice(i, i+search.length).join('') :
arrStr.slice(i).join('');
if(subStr === search){
count++;
arrStr.splice(i, search.length);
}else{
i++;
}
}
return count;
}
let str = 'As sly as a fox, as strong as an ox';
let target = 'as'; // let's look for it
let pos = 0;
while (true) {
let foundPos = str.indexOf(target, pos);
if (foundPos == -1) break;
alert( `Found at ${foundPos}` );
pos = foundPos + 1; // continue the search from the next position
}
同样的算法可以更简洁地呈现:
let str = "As sly as a fox, as strong as an ox";
let target = "as";
let pos = -1;
while ((pos = str.indexOf(target, pos + 1)) != -1) {
alert( pos );
}
"use strict";
var dataFromDB = "testal";
$('input[name="tbInput"]').on("change",function(){
var charToTest = $(this).val();
var howManyChars = charToTest.length;
var nrMatches = 0;
if(howManyChars !== 0){
charToTest = charToTest.charAt(0);
var regexp = new RegExp(charToTest,'gi');
var arrMatches = dataFromDB.match(regexp);
nrMatches = arrMatches ? arrMatches.length : 0;
}
$('#result').html(nrMatches.toString());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">
What do you wanna count <input type="text" name="tbInput" value=""><br />
Number of occurences = <span id="result">0</span>
</div>