C++ Program to Copy Strings

C++ProgrammingServer Side Programming

A string is a one dimensional character array that is terminated by a null character. The value of a string can be copied into another string. This can either be done using strcpy() function which is a standard library function or without it.

The program to copy a string without using strcpy() function is given as follows −

Example

 Live Demo

#include <iostream>
using namespace std;
int main() {
   char str1[100] = "Magic";
   char str2[100];
   int i;
   for(i = 0; str1[i] != '\0'; i++)
   str2[i] = str1[i];
   str2[i] = '\0';
   cout<<"The contents of str2 are: "<<str2;
   return 0;
}

Output

The contents of str2 are: Magic

In the above program, a for loop is used to copy the contents of str1 into str2. This loop runs from 0 till null in str1. After the for loop, null is added to the end of the string in str2 and it is displayed. This is shown as follows.

for(i = 0; str1[i] != '\0'; i++)
str2[i] = str1[i];
str2[i] = '\0';
cout<<"The contents of str2 are: "<<str2;

The program to copy a string using the strcpy() function is given as follows.

Example

 Live Demo

#include <iostream>
#include <cstring>
using namespace std;
int main() {
   char str1[100] = "Magic";
   char str2[100];
   strcpy(str2,str1);
   cout<<"The contents of str2 are: "<<str2;
   return 0;
}

Output

The contents of str2 are: Magic

In the above program, strcpy() function is used to copy the contents of str1 into str2. Then the contents of str2 are displayed. This is shown in the following code snippet.

strcpy(str2,str1);
cout<<"The contents of str2 are: "<<str2;
raja
Published on 05-Oct-2018 07:32:20
Advertisements