In C++, a string is a sequence of characters. Swapping two strings typically involves using a third string as temporary storage. However, it’s possible to swap two strings without using a third string. In this article, we will learn how to do this in C++.
Example
Input: str1 = "Hello" str2 = "world" Output: str1 = "world" str2 = "Hello"
Swapping Strings Without Using a Third String
The XOR algorithm can be used to swap two strings without using a third string. The XOR operation has the property that
A ^ B ^ B = A
which can be used to swap two variables.
Approach
- Iterate through each character of the strings.
- Perform bitwise XOR (^) operation on corresponding characters of the strings.
- Repeat the operation for all characters, effectively swapping their values.
C++ Program to Swap Strings Without Using Third String
C++
// C++ Program to illustrate how to swap strings without // using a third-string #include <iostream> #include <string> using namespace std;
// function to SWap two strings Without Using Third Variable void swapStrings(string& str1, string& str2)
{ int length1 = str1.length();
int length2 = str2.length();
for ( int i = 0; i < length1 && i < length2; ++i) {
str1[i] ^= str2[i];
str2[i] ^= str1[i];
str1[i] ^= str2[i];
}
if (length1 != length2) {
for ( int i = length1; i < length2; ++i) {
str1 += str2[i];
}
for ( int i = length2; i < length1; ++i) {
str2 += str1[i];
}
str1 = str1.substr(0, length2);
str2 = str2.substr(0, length1);
}
} // Driver Code int main()
{ string str1 = "Hello" ;
string str2 = "World" ;
cout << "Before swapping:" << endl;
cout << "String 1: " << str1 << endl;
cout << "String 2: " << str2 << endl;
swapStrings(str1, str2);
cout << "\nAfter swapping:" << endl;
cout << "String 1: " << str1 << endl;
cout << "String 2: " << str2 << endl;
return 0;
} |
Output
Before swapping: String 1: Hello String 2: World After swapping: String 1: World String 2: Hello
Time Complexity: O(max(N,M)), where N and M are the sizes of the strings.
Space Complexity: O(1)