Algorithm
1. Input:
Accept the source string as input.
Determine the length of the source string.
2. Allocate Memory:
Allocate memory for the destination string based on the length of the source string.
3. Copy Operation:
Use a loop to iterate through each character of the source string.
Copy each character to the corresponding position in the destination string.
4. Null Terminator:
After copying all characters, add a null terminator ('\0') at the end of the destination string to mark its end.
5. Output:
Display or use the copied string as needed.
Code Examples
#1 Code Example- C++ programing Copy String Object
Code -
C++ Programming
#include <iostream>
using namespace std;
int main()
{
string s1, s2;
cout << "Enter string s1: ";
getline (cin, s1);
s2 = s1;
cout << "s1 = "<< s1 << endl;
cout << "s2 = "<< s2;
return 0;
}
Copy The Code &
Try With Live Editor
Output
s1 = C++ Strings
s2 = C++ Strings
#2 Code Example- C++ Programing Copy C-Strings
Code -
C++ Programming
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char s1[100], s2[100];
cout << "Enter string s1: ";
cin.getline(s1, 100);
strcpy(s2, s1);
cout << "s1 = "<< s1 << endl;
cout << "s2 = "<< s2;
return 0;
}
Copy The Code &
Try With Live Editor
Output
s1 = C-Strings
s2 = C-Strings
Demonstration
C++ Programing Example to Copy Strings-DevsEnv