How to find out the position of the first appearance of the difference between two lines?

For example, Hello World! and Hi World! - the first occurrence of the difference occurs in the second character. What will be the JavaScript / jQuery function?

+6
source share
4 answers

Assuming that, like other answers, the corresponding lines return -1 :

 // Find common prefix of strings a and b. var prefix = function(a,b){ return a && a[0] === b[0] ? a[0] + prefix(a.slice(1), b.slice(1)) : ''; }; // Find index of first difference. var diff = function(a,b){ return a===b ? -1 : prefix(a,b).length; }; var tests = [ ['Hello World!', 'Hi World!'], ['aaabab', 'aaabzbzz'], ['', ''], ['abc', 'abc'], ['qrs', 'tu'], ['abc', ''], ['', 'abc'] ]; console.log('diff', tests.map(test => diff(test[0], test[1]))); // Or just count up to the first difference // Trickier nested ternary to handle the -1 however. var diff2 = function(a,b){ return a === b ? -1 : a[0] === b[0] ? 1 + diff2(a.slice(1), b.slice(1)) : 0; }; console.log('diff2', tests.map(test => diff2(test[0], test[1]))); 
+2
source

Maybe something like this? It returns in this order the position of the first difference, if any, the length of the shortest string, if they are different, or -1 if it is anyway.

 function findDiff(a, b) { a = a.toString(); b = b.toString(); for (var i = 0; i < Math.min(a.length, b.length); i++) { if (a.charAt(i) !== b.charAt(i)) { return i; } } if (a.length !== b.length) { return Math.min(a.length, b.length); } return -1; } 

Thanks to Phil for the suggestions!

+1
source
 function strDiff(first, second) { if(first==second) return -1; first = first.toString(); second = second.toString(); var minLen = min(first.length,second.length); for(var i = 0; i<minLen; i++) { if(first.charAt(i) != second.charAt(i)) { return i; } } return minLen; } 

Returns -1 if the lines do not differ, or the index (starting from 0) of the character in which they are executed (this is the length of the shortest line if they differ only in different lengths, for example, 'abcd' and 'abcdef' will return 4.

0
source
 function firstDiff(a, b) { var i = 0; while (a.charAt(i) === b.charAt(i)) if (a.charAt(i++) === '') return -1; return i; } 

Returns the position at which the two lines a and b first differ, or -1 if they are equal.

A more effective but less readable version:

 function firstDiff(a, b) { for (var i = 0, c; (c = a.charAt(i)) === b.charAt(i); ++i) if (c === '') return -1; return i; } 

If you feel that you must first argue the arguments, then do this in a call:

 firstDiff(toString(a), toString(b)) 

Most often it will be a waste of time. Know your details!

0
source

Source: https://habr.com/ru/post/886116/


All Articles