Vladimir Khodakovskey Vladimir Khodakovskey - 2 months ago 7
C# Question

How to swap values of two string variables without a temp variable?

For example, I have two string variables:

string a = " Hello ";
string b = " World "


How can I swap it without a temporary variable?

I found an example, but it used a third variable for the length of
a
:

int len1 = a.Length;
a = a + b;
b = a.Substring(0, len1);
a = a.Substring(len1);


How can I do that?

Answer

You can use SubString without using a temp variable, like this:

string a = " Hello ";
string b = " World ";

a = a + b;//" Hello  World "
b = a.Substring(0, (a.Length - b.Length));//" Hello "
a = a.Substring(b.Length);//" World "