Open In App

C# | Swap two Strings without using third user defined variable

Improve
Improve
Like Article
Like
Save
Share
Report

Given two string variables a and b, swap these variables without using a temporary or third variable in C#. Use of library methods is allowed.

Example:

Input:
a = "Hello"
b = "World"

Output:
Strings before swap: a = Hello and b = World
Strings after swap: a = World and b = Hello

The idea is to do string concatenation and then use Substring() method to perform this operation. The Substring() method comes in two forms as listed below:

  • String.Substring Method (startIndex): This method is used to retrieve a substring from the current instance of the string. The parameter “startIndex” will specify the starting position of substring and then substring will continue to the end of the string.
  • String.Substring Method (int startIndex, int length): This method is used to extract a substring that begins from specified position described by parameter startIndex and has a specified length. If startIndex is equal to the length of string and parameter length is zero, then it will return nothing as substring.


Algorithm:

1) Append second string to first string and 
   store in first string:
   a = a + b

2) Call the Substring Method (int startIndex, int length)
   by passing startindex as 0 and length as,
   a.Length - b.Length:
   b = Substring(0, a.Length - b.Length);

3) Call the Substring Method(int startIndex) by passing 
   startindex as b.Length as the argument to store the 
   value of initial b string in a
   a = Substring(b.Length);




// C# program to swap two strings
// without using a temporary variable.
using System;
  
class GFG {
  
    // Main Method
    public static void Main(String[] args)
    {
        // Declare two strings
        String a = "Hello";
        String b = "Geeks";
  
        // Print String before swapping
        Console.WriteLine("Strings before swap: a ="
                          " " + a + " and b = " + b);
  
        // append 2nd string to 1st
        a = a + b;
  
        // store initial string a in string b
        b = a.Substring(0, a.Length - b.Length);
  
        // store initial string b in string a
        a = a.Substring(b.Length);
  
        // print String after swapping
        Console.WriteLine("Strings after swap: a =" +
                          " " + a + " and b = " + b);
    }
}


Output:

Strings before swap: a = Hello and b = Geeks
Strings after swap: a = Geeks and b = Hello


Last Updated : 18 Oct, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads