Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Finding mistakes in a string - JavaScript
We are required to write a JavaScript function that takes in two strings. The first string is some mistyped string and the second string is the correct version of this string. We can assume that the two strings we are getting as argument will always have the same length.
We have to return the number of mistakes that exist in the first string by comparing it character by character with the correct version.
Approach
The solution involves iterating through both strings simultaneously and comparing each character at the same position. When characters don't match, we increment our mistake counter.
Example
Following is the code ?
const str1 = 'Tkos am er exakgrg fetwnh';
const str2 = 'This is an example string';
const countMistakes = (mistaken, correct) => {
let count = 0;
for(let i = 0; i < mistaken.length; i++){
if(mistaken[i] === correct[i]){
continue;
};
count++;
};
return count;
};
console.log(countMistakes(str1, str2));
Output
Following is the output in the console ?
15
How It Works
The function compares each character at position i in both strings. If characters match, it continues to the next position. If they don't match, it increments the count. In our example, 15 out of 25 characters are different between the two strings.
Alternative Approach Using Array Methods
const countMistakesAlt = (mistaken, correct) => {
return [...mistaken].filter((char, index) => char !== correct[index]).length;
};
const str1 = 'Tkos am er exakgrg fetwnh';
const str2 = 'This is an example string';
console.log(countMistakesAlt(str1, str2));
15
Conclusion
Both approaches effectively count character differences between strings. The loop method is more readable, while the array method is more concise using functional programming concepts.
