WAP to copy one string to another
Objective
Write a C++ program to copy one string into another.
Algorithm / Approach
- Declare two strings:
s1ands2. - Read input into
s1. - Use the assignment operator to copy the string:
s2 = s1. - Print the copied string
s2.
main.cpp
#include<iostream>
using namespace std;
int main() {
string s1,s2;
cout<<"Enter a string : ";
getline(cin,s1);
s2 = s1;
cout<<"Copied String : "<< s2;
return 0;
}
Expected Output
Enter a string : cprowess Copied String : cprowess
Explanation of the Program
- In older languages like C, copying a string required manually looping through characters or using
strcpy(). - Because C++ strings are full objects, the assignment operator (
=) is heavily overloaded. When you says2 = s1, C++ automatically handles the memory allocation and perfectly duplicates the string behind the scenes.
Complexity
Time Complexity
O(n) - Where n is the length of the string being copied.
Space Complexity
O(n)