Sunday 29 June 2014

C++ program to copy one string to another

C++ program to copy one string to another string .Here I given four methods to copy one string to another like using strcpy() function, using recursion, using pointers.


Method 1 : C++ program to copy one string to another without using strcpy()
#include<iostream>
using namespace std;
int main()
{
    char str[30],str2[30];
    int i;
    cout<<"Enter String : ";
    cin>>str;
    for(i=0;str[i]!='\0';i++)
        str2[i]=str[i];
    str2[i]='\0';
    cout<<"Copied string is : "<<str2;
    return 0;
}



Method 2 : C++ program to copy one string using strcpy()
#include<iostream>
#include<conio.h>
#include<string.h>
using namespace std;
int main()
{
    char str[20],str2[20];
    int lenght;
    cout<<"Enter String : ";
    cin>>str;
    strcpy(str2,str);
    cout<<"Copied string is : "<<str2;
    return 0;
}



Method 3 : C++ program to copy one string to another using pointers
#include<iostream>
using namespace std;
int main()
{
    char str1[20],str2[20],*p,*q;
    cout<<"Enter string : ";
    cin>>str1;
    p=str1;
    q=str2;
    while(*p!='\0')
    {
        *q=*p;
        q++,p++;
    }
    *q='\0';
    cout<<"Copy of string : "<<str2;
    return 0;
}



Method 4 : C++ program to copy one string to another using recursion
#include<iostream>
using namespace std;
void lenght(char *str,char (&cpy)[50],int i)
{
    if(str[i]=='\0')
    {
        cpy[i]=str[i];
        return ;
    }
    else
        cpy[i]=str[i];
        lenght(str,cpy,i+1);
}
int main()
{
    char str[50],cpy[50];
    cout<<"Enter string : ";
    cin>>str;
    cout<<"Copy of string : ";
    lenght(str,cpy,0);
    cout<<cpy;
    return 0;
}



No comments:

Post a Comment