To swap two strings without using temporary variables, you can try the following code and logic.
Append the second string to the first string.
str1 = str1 + str2;
Set str1 to str2.
str2 = str1.Substring(0, str1.Length - str2.Length);
Now, the final step is to set str2 to str1 −
str1 = str1.Substring(str2.Length);
using System; class Demo { public static void Main(String[] args) { String str1 = "Brad"; String str2 = "Pitt"; Console.WriteLine("Strings before swap"); Console.WriteLine(str1); Console.WriteLine(str2); str1 = str1 + str2; str2 = str1.Substring(0, str1.Length - str2.Length); str1 = str1.Substring(str2.Length); Console.WriteLine("Strings after swap"); Console.WriteLine(str1); Console.WriteLine(str2); } }
The above is the detailed content of Swapping two strings in C# without using temporary variables. For more information, please follow other related articles on the PHP Chinese website!