0

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?

UPD, suggested solution for decimal data type, in ma case i've asked about string data type.

Uladz Kha
  • 2,154
  • 4
  • 40
  • 61

4 Answers4

3

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 "
Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
0

Just use some other means of swapping.

string stringOne = "one";
string stringTwo = "two";

stringOne = stringOne + stringTwo;
stringTwo = stringOne.Substring(0, (stringOne.Length - stringTwo.Length));
stringOne = stringOne.Substring(stringTwo.Length);

// Prints stringOne: two stringTwo: one
Console.WriteLine("stringOne: {0} stringTwo: {1}", stringOne, stringTwo);
astidham2003
  • 966
  • 1
  • 11
  • 33
MikeB0317
  • 1
  • 1
0
   string str1 = "First";
        string str2 = "Second";
        str1 = (str2 = str1 + str2).Substring(str1.Length);
        str2 = str2.Substring(0,str1.Length-1);
Ali Humayun
  • 1,756
  • 1
  • 15
  • 12
0

I'm fond of doing it this way although underneath it's using resources to make it fully thread-safe, and I wouldn't be surprised if it was using a local variable behind the scenes.

string str1 = "First";
string str2 = "Second";
str2 = System.Interlocked.Exchange(ref str1, str2);
Josh Sutterfield
  • 1,943
  • 2
  • 16
  • 25