在不使用数组的情况下获得两个字符串之间的差异

时间:2019-04-08 11:56:57

标签: php

我有两个字符串$ A和$ B,它们按整数排序。实现的函数必须输出{A-B}和{B-A},并且代码必须为WITHARRAYS。有什么想法吗?

输入:

$A = "1 2 3 8 9"; 
$B = "2 5 9 10 12 14";

输出:

{A - B} = "1 3 8"; 
{B - A} = "5 10 12 14";

3 个答案:

答案 0 :(得分:3)

$A = "1 2 3 8 9"; 
$B = "2 5 9 10 12 14";

//Build regular expression pattern from $A
$pattern = "/\b".str_replace(" ", "\b|\b", $A)."\b/";

//Remove matched numbers within word boundaries
$result = preg_replace($pattern, "", $B);

//Remove any unwanted whitespace
$result = trim(preg_replace("!\s+!", " ", $result));

echo "{B - A} = " . $result;

答案 1 :(得分:0)

您可以在循环中为每个字符使用子字符串(并使用ASCII代码)以确定它们是否相等,如果不相同,则将它们写入另一个字符串。如果您的数字大于1个字符,则必须使子字符串寻找下一个空格。

答案 2 :(得分:0)

Here's a looping version using strspn and substr to extract numbers from the strings and substr_replace to remove them when necessary:

$a = "1 2 3 8 9"; 
$b = "2 5 9 10 12 14";

$a_offset = 0;
$b_offset = 0;
while ($a_offset < strlen($a) && $b_offset < strlen($b)) {
    $a_length = strspn($a, '0123456789', $a_offset);
    $a_num = substr($a, $a_offset, $a_length);
    $b_length = strspn($b, '0123456789', $b_offset);
    $b_num = substr($b, $b_offset, $b_length);
    if ($a_num < $b_num) {
        // keep the a value
        $a_offset = $a_offset + $a_length + 1;
    }
    elseif ($b_num < $a_num) {
        // keep the b value
        $b_offset = $b_offset + $b_length + 1;
    }
    else {
        // values the same, remove them both
        $a = substr_replace($a, '', $a_offset, $a_length + 1);
        $b = substr_replace($b, '', $b_offset, $b_length + 1);
    }
}
echo "a - b = $a\nb - a = $b";

Output:

a - b = 1 3 8 
b - a = 5 10 12 14

Demo on 3v4l.org