Uladz Kha
Uladz Kha

Reputation: 2354

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?

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

Upvotes: 0

Views: 2421

Answers (4)

Josh Sutterfield
Josh Sutterfield

Reputation: 1988

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);

Upvotes: 0

Ali Humayun
Ali Humayun

Reputation: 1814

   string str1 = "First";
        string str2 = "Second";
        str1 = (str2 = str1 + str2).Substring(str1.Length);
        str2 = str2.Substring(0,str1.Length-1);

Upvotes: 0

Salah Akbari
Salah Akbari

Reputation: 39946

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 "

Upvotes: 3

MikeB0317
MikeB0317

Reputation: 1

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);

Upvotes: 0

Related Questions