Loading...
C++ Program to Copy Strings

C++ Program to Copy Strings

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

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


Example 1: Program to Copy String Object

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

#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

Example 2: Program to Copy C-Strings

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

#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

Next Example

We hope that this Example helped you develop better understanding of the concept of "Copy Strings" in C++.

Keep Learning : )

In the next Example, we will learn about C++ Sort Elements in Dictionary Order.


- Related Topics