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.

12
  • 4
    first question is. Why do you need to do such thing? Commented Sep 14, 2016 at 19:27
  • 1
    @Steve It's probably some sort of interview question Commented Sep 14, 2016 at 19:27
  • 1
    I think you could use Interlocked.Exchange for that: msdn.microsoft.com/de-de/library/f2090ex9(v=vs.110).aspx Commented Sep 14, 2016 at 19:29
  • you have your answer already. no need of any other thing Commented Sep 14, 2016 at 19:29
  • 2
    Without any further information, I would say the best way is to avoid not using a third variable. There are many (horrible) ways of doing it, but appart from producing unreadable code, cannot see what will be the benefits Commented Sep 14, 2016 at 19:31

4 Answers 4

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 "
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

I don't believe that will compile
0
   string str1 = "First";
        string str2 = "Second";
        str1 = (str2 = str1 + str2).Substring(str1.Length);
        str2 = str2.Substring(0,str1.Length-1);

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.