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 =
Solution 1:
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.
Solution 2:
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.
Post a Comment for "Comparing Two Strings For Identical Values"