-5

How do I swap two strings without using a temporary variable in C#?

string str1 = "First";
string str2 = "Second";
str1 = string.Concat(str1, str2);
str2 = str1.Replace(str2, "");
str1 = str1.Replace(str2, "");
4
  • 4
    What is wrong with your solution? What exactly is your question?
    – lintmouse
    Jan 15, 2016 at 19:28
  • what do you want exactly ? Your question is not clear! Jan 15, 2016 at 19:34
  • 3
    If you're trying to do a coding challenge, that's one thing, but, I suspect that you're doing this out of a misguided attempt to save memory and/or CPU, but, I assure you that using a temporary variable will be the best solution - strings are immutable and you're just storing a reference. You'll actually end up allocating several strings with the solution you and some of the answers have proposed.
    – willaien
    Jan 15, 2016 at 19:45
  • swinging for the Unlikely to be useful for future readers clause for close vote
    – Drew
    Jan 29, 2016 at 21:29

3 Answers 3

2

I would never do the following solution and will also not expect my colleagues to do this kind of swap without using a temporary variable. That is the most simple, clear and far faster solution.

Solution:

string str1 = "First";
string str2 = "Second";
str1 += str2;
str2 = str1.Remove(str1.IndexOf(str2));
str1 = str1.Substring(str2.Length);
1
  • 1
    Fails for "bananas" "ana"
    – stark
    Jul 2, 2016 at 13:05
0

Swapping two string variables without using a temporary variable:

string str1 = "aaac", str2 = "b";

Console.WriteLine(str1);
Console.WriteLine(str2);

str2 = str2 + str1;
str1 = str2.Substring(0,str2.Length - str1.Length);
str2 = str2.Substring(a.Length);

Console.WriteLine("<" + str1 + ">");
Console.WriteLine("<" + str2 + ">");
0

I think there is no way to do this in C#. In Python you can set two variables at the same time, but in C# there is no way. You could create a method to do this more transparently. For sample:

public static void ChangeValues(ref string str1, ref string str2)
{
    var temp = str1;
    str1 = str2;
    str2 = temp;
}

And just call

string str1 = "First";
string str2 = "Second";
ChangeValues(ref str1, ref str2);
Console.WriteLine(str1 + " " + str2);

Not the answer you're looking for? Browse other questions tagged or ask your own question.