Home  >  Article  >  Backend Development  >  Swapping two strings in C# without using temporary variables

Swapping two strings in C# without using temporary variables

王林
王林forward
2023-08-26 15:25:10737browse

在 C# 中不使用临时变量交换两个字符串

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

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

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete