How to Swap Two Strings Without Using Third String in C++?
Last Updated :
29 Feb, 2024
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++
#include <iostream>
#include <string>
using namespace std;
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);
}
}
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)
Share your thoughts in the comments
Please Login to comment...