Skip to main content

ProwessApps

Learn · Practice · Excel

WAP to copy one string to another

C++ Code Example — String Programs

ADVERTISEMENT

WAP to copy one string to another

Objective

Write a C++ program to copy one string into another.

Algorithm / Approach

  1. Declare two strings: s1 and s2.
  2. Read input into s1.
  3. Use the assignment operator to copy the string: s2 = s1.
  4. 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 say s2 = 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)
ADVERTISEMENT