Program to Swap two strings in C++
Written by
There are three tricks through which we swap the strings in C++;
- Three Character Array Method
- Three string method
- Inbuilt swap function
-
Three Character Array Method
In this method,
- We copy the contents of the first string to a temporary array.
- The, we copy the contents of the second array in the first character array.
- Next, we copy the contents of the temporary array to second character array.
Advantage:
- We can use this method to reverse the contents of a numeric array too.
- We do not need to include string library.
Disadvantage:
- High time complexity due to many loops(due to copying array contents).
- Very tedious time-consuming.
-
Three string method
In this method, We use the same technique as above, but we use strings here instead of character arrays.
- We include the string library, and make three objects of String class.
- We use the inbuilt function strcpy() and follow the naïve method of swapping.
Code:
#include <iostream>
#include <cstring> //string library
using namespace std;
int main() { int n; //length of string cin>>n; char s1[n]; char s2[n]; char s3[n]; //temporary string //Input String 1 cin>>s1; //Input String 2 cin>>s2; strcpy(s3,s1); //copy contents of s1 in s3 strcpy(s1,s2); // similar to s1=s2 strcpy(s2,s3); cout<<s1<<"\n"; cout<<s2; return 0; }
Advantage:
- It is faster than the previous method.
Disadvantage:
- We need to use three strings, which is a waste of memory.
-
Inbuilt swap function
In this method, we use the inbuilt swap function to perform the task.
- We include the string library and make two string objects.
- Then, we make use of swap() function and output the strings.
Code:
#include <iostream> #include <string> using namespace std;
int main() { string str1;
string str2; //input string 1 cin>>str1; //input string 2 cin>>str2; str1.swap(str2); //swap contents of str1 and str2 cout<<str1<<"\n"; cout<<str2;
return 0;
}
Advantage:
- It is the fastest of all.
- It uses only two strings to execute the task.