OneBite.Dev - Coding blog in a bite size

Swap A String In C#

Code snippet for how to Swap A String In C# with sample and detail explanation

Swapping strings in C# is a common task encountered by programmers. This short article will provide a simple yet engaging method for doing just that.

Code snippet for Swapping Strings in C#

using System;

class Program
{
    static void Main(string[] args)
    {
        // Initial Strings
        string string1 = "Hello";
        string string2 = "World";

        Console.WriteLine("Before Swapping: String1 = {0}, String2 = {1}", string1, string2);

        // Swapping
        string temporary = string1;
        string1 = string2;
        string2 = temporary;

        Console.WriteLine("After Swapping: String1 = {0}, String2 = {1}", string1, string2);
    }
}

Code Explanation for Swapping Strings in C#

In the provided code snippet, we first set two initial strings, “Hello” and “World,” assigned to string1 and string2, respectively. To demonstrate that these strings have been swapped at the end of our code, we utilize the Console.WriteLine function to print the current state of these variables.

The swapping itself is done through a common programming algorithm called the temporary variable swap. Firstly, we create a new variable named temporary and assign it the value of string1. At this point, we have safely stored the value of string1, allowing us to make the change string1 = string2. Now, string2’s value is in both string1 and string2.

To finish the swap, we need to put string1’s original value - which is currently housed in the temporary variable - into string2. So we make the assignment string2 = temporary.

Once the swap is complete, we again use the Console.WriteLine function to display the final swapped state of the strings. If the swap was successful, string1 should now hold the value “World”, and string2 should now hold the value “Hello”.

c-sharp