String copy in C++
Written by
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:
- Using predefined method strcpy()
- 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:
- Take a string input.
- Initialize another string and name it newstr.
- Call the function strcpy(new_string, old_string)
- 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:
- Take a string input and store it in str
- Find and store the length of the string in a variable
- Initialize another string and name it newstr.
- Create a function which takes str and len as arguments and prints the copied string.
- 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