Swapping two strings in C# without using temporary variables

王林
Release: 2023-08-26 15:25:10
forward
764 people have browsed it

在 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;
Copy after login

Set str1 to str2.

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

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

str1 = str1.Substring(str2.Length);
Copy after login

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);
   }
}
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!