在Java中交换两个字符串,而无需使用第三变量,并且在Java中不使用任何Insuild API

发布于 2025-01-25 18:08:53 字数 300 浏览 1 评论 0原文

最近,我进行了一次面试,他们要求我在不使用任何第三变量的情况下交换两个字符串,并且不使用任何字符串方法,例如子字符串,替换或不使用StringBuilderstringbuffer

例如:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

南风几经秋 2025-02-01 18:08:53

这是利用分配表达式(和评估顺序)的技巧:

str2 = (new String[] { str1, (str1 = str2) })[0];

肯定可以有很多变化,但这是这样做的。

Here's a trick that exploits assignment expressions (and evaluation order):

str2 = (new String[] { str1, (str1 = str2) })[0];

There surely can be many variations of that, but that does it.

江心雾 2025-02-01 18:08:53

做了一些有线实践后,我使用三元操作员获得了另一种扭曲的解决方案。

解决方案:
str1 = str2 +(( str2 = str1 )! “ ”);

After doing some wired practicals I got one more wried solution using Ternary Operator.

Solution:
str1 = str2 + ( (str2= str1) != null ? "":"");

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文