4

我试图了解如何编写以下涉及交换/交换运算符的语句的逻辑。到目前为止,我已经用谷歌搜索并搜索了文本(Java 解决问题的介绍),但没有任何运气。以前有没有人在以下问题上苦苦挣扎,也许找到了答案(这是字符串的一个例子,但我一般都在使用 temp 的交换运算符苦苦挣扎):

有两个字符串变量 s1 和 s2 已经被声明和初始化。编写一些代码来交换它们的值。

我知道我应该使用临时变量,而这正是我的逻辑为空的地方。

我写它的方式,我知道它的错误如下:

temp = s1;
s2 = temp;
4

4 回答 4

3

在您不正确的解决方案中,您失去了s2. 您想使用temp保留任一变量的值,以便在交换期间不会丢失该值。

以下是您需要做的事情的清单:

  • 复制s1某处的值。
  • s1现在,使用stashed的副本,您可以分配s1.s2
  • 现在分配给s2您制作的副本s1
于 2012-07-21T19:02:26.323 回答
2

为了完整起见,当您不需要临时变量时,有一种特殊情况。

当您要交换的两个值长度相等并且语言允许您对它们使用按位运算符时,您可以进行XOR 交换

A = A bitwise xor B
B = A bitwise xor B
A = A bitwise xor B

尽管在现代计算机上这很少实用,但了解并演示 XOR 操作的一个有趣方面是件好事。

于 2012-07-21T21:44:03.313 回答
0

将变量视为只能容纳一件事的容器。要交换两个变量的值,您需要三个容器。

String s1 = "Some string", s2 = "Another string", tmp;
tmp = s1; // put the first item into the third bin
s1 = s2; // put the second item into the first bin
s2 = tmp; // put the first item into the second item
于 2012-07-21T19:02:25.753 回答
0

在所有语言中:

temp = s1; // temporarily store the s1 value because we'll replace it next
s1 = s2; // now s1 lost it's value, and got a new one
s2 = temp; // luckily s2 doesn't go home empty handed, the temp is still good
于 2012-07-21T19:02:27.667 回答