Anda cukup menyalin objek string di C ++ menggunakan = operator penugasan.


Contoh 1: Salin Objek String

#include 
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;
}

Keluaran

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

Untuk menyalin c-string di C ++, strcpy() fungsi digunakan.


Contoh 1: Salin C-Strings

#include 
#include 

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;
}

Keluaran

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