tags:

views:

816

answers:

6

I'm looking for an easy way to compare two similar strings and output the difference for instance if I have

"abcdefghijklmnop" and "abcdefghi"

the function would output

"jklmnop"

I need to know how to do this in both php and python

+4  A: 

In PHP. array_diff compares the first against the second array and returns the difference.

$a1 = str_split('abcdefghijklmnop');
$a2 = str_split('abcdefghi');

echo join('', array_diff($a1, $a2)); // jklmnop

This will work as well.

$s1 = 'abcdefghijklmnop';
$s2 = 'abcdefghi';

echo str_replace(str_split($s2), '', $s1); // jklmnop

This could handle $s2 = 'ghiabcdef'; as well because str_replace() is fed with an array, not a string.

Philippe Gerber
+1  A: 

In Python, you can do:

x = "abcdefghijklmnop"
y = x.replace("abcdefghi", "")

# y now equals "jklmnop"
Mike Trpcic
A: 
>>> s1 = "abcdefghijklmnop"
>>> s2 = "abcdefghi"
>>> s1.strip(s2)
'jklmnop'
b3rx
This only works if `s2` is at the beginning or end.
Evan Fosmark
+5  A: 

Python has the difflib module in its standard library that can be used to do this.

import difflib

s1 = "abcdefghijklmnop"
s2 = "abcdefghi"
s = difflib.SequenceMatcher(s1, s2)
for block in s.get_matching_blocks():
    print "match of length %d at a[%d] and b[%d]" % block

difflib is very powerful and has many different ways of searching for differences. Some study of the documentation would be worthwhile if you choose to use this.

Greg Hewgill
Because in Python, it really is simply a case of typing "import antigravity"!
Sean Vieira
A: 

In Python:

>>> s1 = 'abcdefghijklmnop'
>>> s2 = 'abcdefghi'
>>> set(s1) - set(s2)
set(['k', 'j', 'm', 'l', 'o', 'n', 'p'])
Bastien Léonard
This implies that there's only one occurrence of each letter in each string.
Evan Fosmark
A: 

In Python:

string1 = "abcdefghijklmnop"
string2 = "abcdefghi"

def stringComp(string1, string2):
   if len(string1.split(string2)) > 0:
    if string1 == string1.split(string2)[0]:
     finalstring = stringComp(string2, string1)
    else:
     finalstring = ''.join(string1.split(string2))
   else:
      finalstring = ""
   return finalstring

This should always give you the difference in the strings. However, I'm sure there is a much easier way to do this.

Sean Vieira