methuselah
methuselah

Reputation: 13206

Comparing two strings for identical values

// 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?");

compareNum = 0;

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

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

I've managed to build a relatively simple string comparison 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!

Upvotes: 4

Views: 14825

Answers (2)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324640

Well you are comparing 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?");
compareNum = 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)) compareNum++;
}

// do something with compareNum.

Upvotes: 9

Dave Newton
Dave Newton

Reputation: 160191

You're looping over each character in string 1 and comparing 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.

Upvotes: 2

Related Questions