-3

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

4

4 回答 4

1

我会这样做:

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);
于 2013-09-13T07:53:48.120 回答
0

在您精确之后,这是我的解决方案:

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

于 2013-09-13T08:19:52.923 回答
0

使用similar_text()函数

<?php
    echo "character count: ". similar_text("Mack","Michelle");
?>

输出

character count: 2
于 2013-09-13T07:54:48.037 回答
0

我需要更多示例来确保它有效,但使用正则表达式可能对您有用:

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
于 2013-09-13T08:23:45.247 回答