在Java中交换两个字符串,而无需使用第三变量,并且在Java中不使用任何Insuild API
最近,我进行了一次面试,他们要求我在不使用任何第三变量的情况下交换两个字符串,并且不使用任何字符串方法,例如子字符串,替换或不使用StringBuilder
和stringbuffer
。
例如:
String str1 = "hello";
String str2 = "morning";
输出:
String str1 = "morning";
String str2 = "hello";
Recently I have given an interview where they have asked me to swap two String without using any third variable and without using any String method like substring, replace or without using StringBuilder
and StringBuffer
.
Eg:
String str1 = "hello";
String str2 = "morning";
output:
String str1 = "morning";
String str2 = "hello";
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是利用分配表达式(和评估顺序)的技巧:
肯定可以有很多变化,但这是这样做的。
Here's a trick that exploits assignment expressions (and evaluation order):
There surely can be many variations of that, but that does it.
做了一些有线实践后,我使用三元操作员获得了另一种扭曲的解决方案。
解决方案:
str1 = str2 +(( str2 = str1 )! “ :”);
After doing some wired practicals I got one more wried solution using Ternary Operator.
Solution:
str1 = str2 + ( (str2= str1) != null ? "":"");