C++ Program to Copy Strings

In this example, you will learn to copy strings (both string objects and C-style strings).

To understand this example, you should have the knowledge of following C++ programming topics:

You can simply copy string objects in C++ using = assignment operator.


Example 1: Copy String Object

#include <iostream>
using namespace std;

int main()
{
    string s1, s2;

    cout << "Enter string s1: ";
    getline (cin, s1);

    s2 = s1;

    cout << "s1 = "<< s1 << endl;
    cout << "s2 = "<< s2;

    return 0;
}

Output

Enter string s1: C++ Strings
s1 = C++ Strings
s2 = C++ Strings

To copy c-strings in C++, strcpy() function is used.


Example 1: Copy C-Strings

#include <iostream>
#include <cstring>

using namespace std;

int main()
{
    char s1[100], s2[100];

    cout << "Enter string s1: ";
    cin.getline(s1, 100);

    strcpy(s2, s1);

    cout << "s1 = "<< s1 << endl;
    cout << "s2 = "<< s2;

    return 0;
}

Output

Enter string s1: C-Strings
s1 = C-Strings
s2 = C-Strings