Skip to content
Advertisement

Difference String on Postgres

I have two string that contain one and zeros. I want to determine how many chars are different the same position. For example:

“0000111000000000000000000000000000000000000000000000000000000000” AND “0000000000000010000110000111100000000000000000000000000000000000”

The result is: 10

These strings’ length are 64 always;

I can do it with loop which iterate over the string and count difference. but i want to do it with reg exp or another tool. The speed is important me. Because i have a lot of data to compare.

Advertisement

Answer

Cast the strings to bit(64), use bitwise XOR, cast the result to text and count the 1 chars:

select length(replace(
    ( '0000111000000000000000000000000000000000000000000000000000000000'::bit(64)
    # '0000000000000010000110000111100000000000000000000000000000000000'::bit(64))::text,
    '0', ''))

 length 
--------
     10
(1 row)     
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement