CPP Program copy a string in three different ways

 In this program, discussion about how to copy the string in the three different methods in the cpp programming language.


Ist method: string object

Code:

#include <iostream>

using namespace std;


int main()

{

    string str1, str2;


    cout << "Enter string s1: ";

    getline (cin, str1);


    str2 = str1;


    cout << "string1 = "<< str1 << endl;

    cout << "string2 = "<< str2;


    return 0;

}



Second method: Copy c string

Code:

#include <iostream>

#include<cstring>

using namespace std;


int main()

{

    char str1[100], str2[100];


    cout << "Enter string s1: ";

    cin.getline(str1,100);


    strcpy(str2,str1);


    cout << "string1 = "<< str1 << endl;

    cout << "string2 = "<< str2;


    return 0;

}


3RD METHOD: By using loop

Code:

#include <iostream>

#include<cstring>

using namespace std;


int main()

{

    char str1[100], str2[100];


    cout << "Enter string s1: ";

    cin.getline(str1,100);


    for(int i=0;str1[i]!='\0';i++)

    {

     str2[i]=str1[i];

}


    cout << "string1 = "<< str1 << endl;

    cout << "string2 = "<< str2;


    return 0;

}



Comments

Hire a programmer

Popular posts from this blog

CSS selector

C program to convert decimal to binary number

C Program to convert binary to decimal number