0

How would I compare two strings and get the quantity of letters or numbers equal to each other?

let's say I have two strings. for example "gjiebbz686wh39n" and "girjskjhgffh8yg". How would I compare which numbers or letters were equal to each other and return the result? like in a XOR gate. If stacked on top of each other two of the same character = 1 or two different = 0. For arguments sake both strings are equal in number of characters. gjiebbz686wh39n girjskjhgffh3yg 100000000001100 the result on the above would be 3 for example.

24th Jan 2018, 9:41 PM
Crypto Man
9 Answers
+ 3
In C: char *comp(char *str1, char *str2, int len) { int i; char result[len]; for(i=0, i<len;++i) if (str1[i] == str2[i]) result[i] = '1'; else result[i] = '0'; return result; } Or, if you want to return the nr of characters which are the same: int comp(char *str1, char *str2, int len) { int i, result = 0; for(i=0, i<len;++i) if (str1[i] == str2[i]) ++result; return result; }
24th Jan 2018, 9:52 PM
Vlad Serbu
Vlad Serbu - avatar
+ 9
no, it should be almost identical to Vlads code. var length1 = string1.length; for(let i = 0; i < length1; ++i) { alert(string1[i]); }
25th Jan 2018, 12:57 AM
jay
jay - avatar
+ 5
@Crypto Man: I believe you would have to write the equivalent function is js to perform this task
24th Jan 2018, 10:03 PM
jay
jay - avatar
+ 5
I would make a third string equal to the length of the longer of the two strings setting all values in it equal to zero. then do an index compare of the other two strings in all cases where they are equal set the third strings index to one.
25th Jan 2018, 1:25 AM
Michael Simnitt
Michael Simnitt - avatar
+ 5
str1 ="abcdef"; str2 ="abcgtfy"; length = (str1.length > str2.length)?str1.length : str2.length; console.log("longer string:"+length ) let count = 0; for(let i=0; i<length;i++){ if(str1[i] == str2[i]){ count++; } } console.log("same count:"+count) Here is a js example of how to do it https://code.sololearn.com/WmNz43Yc3JSK/?ref=app
25th Jan 2018, 2:08 AM
Michael Simnitt
Michael Simnitt - avatar
+ 2
Would this be similar for JavaScript or is there a ready built function for such things?
24th Jan 2018, 9:57 PM
Crypto Man
+ 1
Brilliant, thanks Jay
25th Jan 2018, 12:58 AM
Crypto Man
+ 1
oh yeah, sorry still working this out
25th Jan 2018, 1:00 AM
Crypto Man
+ 1
thanks Michael, the zeros and ones are just a reference to true or false really. I just needed to get the total number of same values. I'll definitely keep this in mind though. It may come in useful if I extend the app to use hardware.
25th Jan 2018, 1:29 AM
Crypto Man