Swap two string values without using a temporary variable

how can i swap two string values without using a temporary variable, any in C/C++/C#/VB?

string string1 = "The quick brown fox jumps over the lazy dog";
string string2 = "Hello world!";
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Éric MoreauSenior .Net ConsultantCommented:
Hi doc_jer,

This is a very theorical question. Are you doing homeworks?

The trick here is to add the content of string2 to string1 after a delimiter, move the left portion (up to the delimiter) to string1 and remove the left part (including the delimiter) from string2.

There's always going to be some temp storage, whether explicit or implicit.  In the .NET flavors, there will be even more.

The only reason I can think of for posing such a quiestion to a class is to show there are often several ways to deal with a problem, the best of which is usually the cleanest, easiest to read.  In this case, using an explicit intermediate.

doc_jerAuthor Commented:
i can swap two integer values using XOR, but not in string.
Amazon Web Services

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

You can use xor if the strings are the same length and mutable.
You don't mention which language you are using, so I don't know
if string objects are mutable or immutable in your language.

Alright, I am giving the stuff in java so that you can convert it into any other language specific logic. The code flows like this in JAVA.

public class stringdemo {
      public static void main(String[] a1){
            String a = "shyam";
            String b = "hai";
            System.out.println(a + " " + b);

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
s1 and s2 are the pointers to string objects, right?
so, swap those two pointers and thats it :)

that's the same problem like swapping the two numbers ;)

good luck ;)
Keeping in mind that gcmachel's solution is probably the most portable ...
To follow on from doc_jer's & brettmjohnson's posts - you could achieve this by:
1) pad the shorter string to the length of the longer string, using some delimiting character known not to be in the other string (eg \0 or \h)
2) for each character XOR the ascii codes in that position

Here's some really horrendously inefficient VB code that will do the job

Private Sub Reverse(s1 As String, s2 As String)
Dim i As Integer

    If Len(s1) < Len(s2) Then
        s1 = s1 & String(Len(s2) - Len(s1), Chr(8))
    ElseIf Len(s2) < Len(s1) Then
        s2 = s2 & String(Len(s1) - Len(s2), Chr(8))
    End If
    For i = 1 To Len(s1)
        Mid(s1, i, 1) = Chr((Asc(Mid(s1, i, 1)) Xor Asc(Mid(s2, i, 1))) Xor Asc(Mid(s2, i, 1)))
        Mid(s2, i, 1) = Chr((Asc(Mid(s2, i, 1)) Xor Asc(Mid(s1, i, 1))) Xor Asc(Mid(s1, i, 1)))
    i = InStr(s1, Chr(8))
    If i > 0 Then
        s1 = Left(s1, i - 1)
        i = InStr(s2, Chr(8))
        If i > 0 Then
            s2 = Left(s2, i - 1)
        End If
    End If
 End Sub

This isn't really within the spirit of the original challenge, as it uses an additional integer variable - in the real world, assuming you wanted to do this for some reason, you'd use intermediate variables to avoid repeatedly taking ASC values, etc.  All in all, I'd go with gcmachel's solution!
you're all using additional variables indirectly :)
the goal is "how can i swap two string values without using a temporary variable"
Am I the only one who understands (or doesn't understand) this? :D
well, i guess the question then is to swap two strings without consuming additional storage? Although gmachel's solution didn't use a temp variable (nice job) it still uses storage equal to the size of one of the strings.

I thought about this for a bit and it seems to me that there is no avoiding it. Either you're gonna end up consuming heap space (variable) or stack space (passing data between functions).

if you just exchange pointers to those strings, no additional memory is consumed.
Éric MoreauSenior .Net ConsultantCommented:
the pointers are not available in all the languages enumerated by the asker.

besides, swapping pointers just minimizes the amount of temp storage you need, right? You would still need temp storage to store one of the pointers. Unless you're thinking of some cool arithmetic?
In VB.NET, use a boolean (ex. Dim anotherString as Boolean) and an If statement.


If (anotherString = 1) Then
string string1 = "The quick brown fox jumps over the lazy dog"
string string2 = "Hello world!"
ElseIf (anotherString = 1) The
string string1 = "Hello world!"
string string2 = "The quick brown fox jumps over the lazy dog"
End If
emoreau: "the pointers are not available in all the languages enumerated by the asker."

  In which one?

MarkoBarko: "besides, swapping pointers just minimizes the amount of temp storage you need, right? You would still need temp storage to store one of the pointers. Unless you're thinking of some cool arithmetic?"

  There was a question here (try searching) about swapping two numbers (variables) without the temp variable. Since the pointers are nothing but the numbers, you can use XOR to exchange the pointers as well as the numbers, or you can use this logic, if you don't prefer XOR:

A := aa;
B := bb;

A := A + B; // aa+bb
B := A - B; // aa+bb-bb = aa
A := A - B; // aa+bb-aa = bb

so, you see: B=aa, A=bb. Got it?
Éric MoreauSenior .Net ConsultantCommented:
>>In which one?

VB does not support pointer directly.
what do you mean by "directly"
are you saying that there is no any kind of typecast in VB?

as far as i know, every programming language has a way
to typecast one type to another, simmilar type, cause without
it, it wouldn't be of much use..

anyway, I think we should stop arguing and let the author of
this question decides. I'm just saying that every solution from
above uses at least one additional temp variable, which was
explicitly told not to be used.
doc_jerAuthor Commented:
actually guys, i also did the above samples before. im just thinking only a trick for this...
by the way i have to give the points now.

thanks for your ideas.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.