Swap two Strings without using temp variable in C#


To swap two strings without using a temp variable, you can try the following code and logic.

Append the second string with the first.

str1 = str1 + str2;

Set the str1 in str2.

str2 = str1.Substring(0, str1.Length - str2.Length);

Now, the final step is to set str2 in str1 −

str1 = str1.Substring(str2.Length);

Example

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);
   }
}

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 21-Jun-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements