how swap two strings without using 3rd variable? could it be done using constructors?
if yes how?
Printable View
how swap two strings without using 3rd variable? could it be done using constructors?
if yes how?
If you are dealing with C-style null terminated strings, and have a pointer to the first character of each string, then you could just swap the pointers. If you are dealing with std::string objects, then just use std::swap as the underlying swap is likely to swap pointers rather than perform a full copy with a third string.
string for example : "qwerty"
Run that example. Is this what you're asking?Code:#include <string>
#include <iostream>
using namespace std;
int main()
{
string s1 = "abc";
string s2 = "123";
cout << s1 << " " << s2 << "\n";
swap(s1, s2);
cout << s1 << " " << s2 << "\n";
}
Regards,
Paul McKenzie
as a general rule... NO.
Swapping in C/C++ always requires a temporary.
std::swap() just works around the issue, it still uses a temporary, you just didn't define it yourself.
You might be able to pull some "weird" binary or mathematical trick to swap SOME types of variables, but chances are this'll be less efficient in the end than using a temporary for the swap.
That's why I was asking what type of string. You could possibly do it with some combination of concatenating, copying and shifting.
The only situation where it is possible to swap standard null terminated strings without using a 3rd variable is when they are exactly the same size (or the memory allocated for the smaller string is at least that of the larger string). See example below. This also assumes that the max ASCII value of any individual char in the string is 127 otherwise *p1 += *p2 will overflow the bounds of a char.
Code:#include <iostream>
using namespace std;
int main ()
{
char s1[10] = "abcdef";
char s2[10] = "ghijkl";
cout << "before swap" << endl << s1 << endl << s2 << endl;
for (char *p1 = s1, *p2 = s2; *p1; p1++, p2++) {
*p1 += *p2;
*p2 = *p1 - *p2;
*p1 -= *p2;
}
cout << endl << "after swap" << endl << s1 << endl << s2 << endl;
return (0);
}
Perhaps it doesn't even need to be as nifty as 2kaud's proposal, in case that no temporary string variable (of whatever concrete type) is allowed, while a temporary char variable is...
The XOR swap (without a temp) doesn't have this limitation,
http://en.wikipedia.org/wiki/XOR_swap_algorithm