String copy in C++

Written by

Juhi Kamdar

C++ Copy string program using pre-defined and user defined methods

Here we’ll write a program to copy a string into another string.

In order to perform this, we can use one of the following methods:

  1. Using predefined method strcpy()
  2. Without using the predefined method/using user-defined function

Method 1: Using the predefined method

Logic: In this method, we’ll use predefined function strcpy() which takes two arguments.

Strcpy(destination string, source string)

Note: This method does not return any value.

Algorithm:

  1. Take a string input.
  2. Initialize another string and name it newstr.
  3. Call the function strcpy(new_string, old_string)
  4. Print the new string, newstr.

Code:

#include<iostream,h>
#include<string.h>
void main()
{
	string str,newstr;
	cout<<"Enter a string: ";
	getline(cin,str);
	strcpy(newstr, str);   //performing string copy
	cout<<"The copied string is: "<< newstr;
}

Output:

Enter a string: Beijing
The copied string is: Beijing

Method 2: Without Using predefined method/Using user-defined method

Logic: In this method, we use the naïve approach of copying each character of a string in a new string using a loop.

Algorithm:

  1. Take a string input and store it in str
  2. Find and store the length of the string in a variable
  3. Initialize another string and name it newstr.
  4. Create a function which takes str and len as arguments and prints the copied string.
  5. Print the new string, newstr.

Code:

#include<iostream>
#include<string>
using namespace std;
void copy(string str, int len)
{
	string newstr;
	int i;
	for(i=0; i<len; i++)//copying characters in newstr
		newstr[i] = str[i]; //we can also use concatenation on an empty string
	newstr[i] = '\0'; //terminating string
	cout<<"\n The copied string is: "<<newstr;
}
int main()
{
	string str;
	int len;
	cout<<"Enter a string: ";
	getline(cin,str);
	len=str.length();
	copy(str,len);
	return 0;
}

Output:

Enter a string: Studymite
The copied string is: Studymite
String copy in C++