Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
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);
}
} Advertisements
