I need to find the no. of similar characters between two strings using JS/PHP
Example str1: Mack str2: Michelle
Similar Characters: "M" "C" similar character count: 2
I need to find the no. of similar characters between two strings using JS/PHP
Example str1: Mack str2: Michelle
Similar Characters: "M" "C" similar character count: 2
我会这样做:
str1 = str1.toUpperCase();
str2 = str2.toUpperCase();
var counter = 0;
var min = Math.min(str1.length, str2.length);
for(var i = 0; i < min; i++)
{
if(str1.charAt(i) === star2.charAt(i))
counter++;
}
alert("Result: "+counter);
在您精确之后,这是我的解决方案:
str1 = str1.toUpperCase();
str2 = str2.toUpperCase();
var counter = 0, find = -1;
for(var i = 0; i < str1.length; i++)
{
find = str2.indexOf(str1.charAt(i));
if(find > -1)
{
counter++;
str2 = str2.substr(0, find) + str2.substr(find + 1);
}
}
alert("Result: "+counter);
它适用于您给我们的 2 个示例:
米歇尔和米歇尔 = 8 斯内哈和纳文 = 3
使用similar_text()函数
<?php
echo "character count: ". similar_text("Mack","Michelle");
?>
输出
character count: 2
我需要更多示例来确保它有效,但使用正则表达式可能对您有用:
function similar_text_regex(str1, str2){
var regEx = new RegExp('['+str2+']', 'gi');
var matchCnt = str1.match(regEx2).length;
return matchCnt;
}
console.log(similar_text_regex('Michelle', 'Michellle')); // --> 8
console.log(similar_text_regex('Jason', 'Jane')); // --> 3
console.log(similar_text_regex("sneha","naveen")); // --> 3