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.
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.
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);
Strings before swap: a = Hello and b = Geeks Strings after swap: a = Geeks and b = Hello
- C# | How to get Third Element of the Tuple?
- How to get third Element of the ValueTuple in C#?
- C# | Remove elements from a HashSet with conditions defined by the predicate
- C# | Remove all elements of a List that match the conditions defined by the predicate
- Program to swap numbers using XOR operator in C#
- C# | How to play user modified Beep sound through Console
- How to implement is functionality without using is keyword in C#
- C# | How to use strings in switch statement
- C# | Get the number of strings in StringCollection
- C# | Remove all the strings from the StringCollection
- C# | Arrays of Strings
- Interpolated Verbatim Strings in C# 8.0
- C# | Check if two SortedList objects are equal
- C# | Check if two String objects have the same value | Set-1
- C# | Check if two ListDictionary objects are equal
- Checking if two ValueTuple<T1,T2,T3,T4> are equal or not in C#
- C# | Union of two HashSet
- C# | Intersection of two HashSets
- C# | Check if two HashSet<T> objects are equal
- C# | Check if two BitArray objects are equal
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.