最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Comparing two strings for identical values - Stack Overflow

programmeradmin3浏览0评论
// Write a program to check whether or not two arrays are identical in size, and hold identical values

string1 = prompt("String 1?");
string2 = prompt("String 2?");

pareNum = 0;

for(i=0; i<string1.length; i++)
{
    for(j=i; j<string2.length; j++)
    {
    if (string1.charAt(i) == string2.charAt(j))
{
        pareNum++;
        break;
}
    }
};

alert("We found " + pareNum + " identical value(s).");

I've managed to build a relatively simple string parison program but now the problem I have is the result it outputs.

For example if I type in "Jeansy" and "Jeansy" - I get the response of "We found 6 identical values."

Whereas if I type in "Molanza" and "Molanza" - I get the reply of "We found 9 identical values."

Surely it should only be 7?

Or does the 'a' get counted twice? Is there anyway I can negate this?

Btw I'm taking into account all strings.

Thanks in advance!

// Write a program to check whether or not two arrays are identical in size, and hold identical values

string1 = prompt("String 1?");
string2 = prompt("String 2?");

pareNum = 0;

for(i=0; i<string1.length; i++)
{
    for(j=i; j<string2.length; j++)
    {
    if (string1.charAt(i) == string2.charAt(j))
{
        pareNum++;
        break;
}
    }
};

alert("We found " + pareNum + " identical value(s).");

I've managed to build a relatively simple string parison program but now the problem I have is the result it outputs.

For example if I type in "Jeansy" and "Jeansy" - I get the response of "We found 6 identical values."

Whereas if I type in "Molanza" and "Molanza" - I get the reply of "We found 9 identical values."

Surely it should only be 7?

Or does the 'a' get counted twice? Is there anyway I can negate this?

Btw I'm taking into account all strings.

Thanks in advance!

Share Improve this question edited Oct 30, 2011 at 0:09 methuselah asked Oct 29, 2011 at 23:13 methuselahmethuselah 13.2k52 gold badges176 silver badges332 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 9

Well you are paring every letter in string1 with every letter in string2. If there are duplicate letters you'll get duplicate results.

Try this:

string1 = prompt("String 1?");
string2 = prompt("String 2?");
pareNum = 0; // why are you using the Number contructor? Unneeded.

l = Math.min(string1.length, string2.length);
for( i=0; i<l; i++) {
    if( string1.charAt(i) == string2.charAt(i)) pareNum++;
}

// do something with pareNum.

You're looping over each character in string 1 and paring it to each character in string 2--but you're looping over string 2 for every character in string 1.

The indices for each string should be the same; you don't need two loops.

How you handle strings whose lengths are different depends on your requirements.

发布评论

评论列表(0)

  1. 暂无评论