Find first character that is different between two strings

后端 未结 4 1204
心在旅途
心在旅途 2020-11-28 20:14

Given two equal-length strings, is there an elegant way to get the offset of the first different character?

The obvious solution would be:

for ($offs         


        
4条回答
  •  一个人的身影
    2020-11-28 20:32

    If you convert a string to an array of single character one byte values you can use the array comparison functions to compare the strings.

    You can achieve a similar result to the XOR method with the following.

    $string1 = 'foobarbaz';
    $string2 = 'foobarbiz';
    
    $array1 = str_split($string1);
    $array2 = str_split($string2);
    
    $result = array_diff_assoc($array1, $array2);
    
    $num_diff = count($result);
    $first_diff = key($result);
    
    echo "There are " . $num_diff . " differences between the two strings. 
    "; echo "The first difference between the strings is at position " . $first_diff . ". (Zero Index) '$string1[$first_diff]' vs '$string2[$first_diff]'.";

    Edit: Multibyte Solution

    $string1 = 'foorbarbaz';
    $string2 = 'foobarbiz';
    
    $array1 = preg_split('((.))u', $string1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
    $array2 = preg_split('((.))u', $string2, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
    
    $result = array_diff_assoc($array1, $array2);
    
    $num_diff = count($result);
    $first_diff = key($result);
    
    echo "There are " . $num_diff . " differences between the two strings.\n";
    echo "The first difference between the strings is at position " . $first_diff . ". (Zero Index) '$string1[$first_diff]' vs '$string2[$first_diff]'.\n";
    

提交回复
热议问题