Php 在不使用数组的情况下获取两个字符串之间的差异
我有两个按整数排序的字符串$A和$B。实现的函数必须输出{A-B}和{B-A},并且代码必须没有数组。有什么想法吗 输入:Php 在不使用数组的情况下获取两个字符串之间的差异,php,Php,我有两个按整数排序的字符串$A和$B。实现的函数必须输出{A-B}和{B-A},并且代码必须没有数组。有什么想法吗 输入: $A = "1 2 3 8 9"; $B = "2 5 9 10 12 14"; 输出: {A - B} = "1 3 8"; {B - A} = "5 10 12 14"; 您可以在循环中为每个字符使用子字符串(并使用ASCII代码)来确定它们是否相等,如果它们不相同,则将它们写入另一个字符串。如果您的数字大于1个字符,则必须使子字符串查找下一个空格。这是一个循环
$A = "1 2 3 8 9";
$B = "2 5 9 10 12 14";
输出:
{A - B} = "1 3 8";
{B - A} = "5 10 12 14";
您可以在循环中为每个字符使用子字符串(并使用ASCII代码)来确定它们是否相等,如果它们不相同,则将它们写入另一个字符串。如果您的数字大于1个字符,则必须使子字符串查找下一个空格。这是一个循环版本,使用and从字符串中提取数字,并在必要时将其删除:
$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;
$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";
您必须向我们展示您的一些代码工作,以便我们能够纠正这一点。否则,您似乎要求我们为您编写代码。您可以使用explode。数组_diff(explode(“,$A),eplode(“,$B))@TrueTiem:OP不想使用array@devpro实际上它不是数组,还是字符串。只有在使用array_diffcode时才转换为array必须没有array@TrueTiemI认为我可以使用explodefunction@eoitos
explode
的返回值是什么类型的…?注释中提到了许多不同的方法,我也建议使用explode,但此函数通过选定的字符将字符串转换为数组。你的问题是一个没有数组的Answer。没错!没有数组。。。这并不容易,我花了3天的时间,但我还没有找到工作solution@eoitos我很高兴能帮上忙!如果答案解决了你的问题,请不要忘记点击左边的复选标记来接受我的答案。
a - b = 1 3 8
b - a = 5 10 12 14