In this code we will copy string without using strcpy()
#include <iostream>
using namespace std;
int main(){
char arr1[100],arr2[100];
int i;
cout<<"Enter string"<<endl;
cin>>arr1;
for( i=0; arr1[i] != '\0'; ++i)
{
arr2[i] = arr1[i];
}
arr2[i] = '\0';
cout<<arr1<<" = Array 1 String"<<endl;
cout<<arr2<<" = Array 2 string Copied"<<endl;
return 0;
}
Explanation:
- Declare Two Character Arrays:
arr1[100]: This array will store the string input by the user.arr2[100]: This array will store the copied string.
- User Input:
- The program asks the user to enter a string and stores it in
arr1. - The
cininput will stop reading when it encounters whitespace (like a space or newline), so the user can enter a word without spaces.
- The program asks the user to enter a string and stores it in
- Copy the String:
- A
forloop is used to copy each character fromarr1toarr2. - The loop runs until it reaches the null character (
\0), which marks the end of the string in C++. - After copying all characters, it assigns
\0to the end ofarr2to properly terminate the string.
- A
- Display Both Strings:
- The program prints the original string (
arr1) and the copied string (arr2).
- The program prints the original string (
Example :
- The user enters the string “hello”.
arr1 = "hello"
- The
forloop starts copying each character:- First iteration:
arr2[0] = arr1[0] = 'h' - Second iteration:
arr2[1] = arr1[1] = 'e' - Third iteration:
arr2[2] = arr1[2] = 'l' - Fourth iteration:
arr2[3] = arr1[3] = 'l' - Fifth iteration:
arr2[4] = arr1[4] = 'o' - The loop stops when it encounters the null character (
arr1[5] = '\0'), so the program adds\0at the end ofarr2.
- First iteration:
- The output will be:
Output:
hello = Array 1 String
hello = Array 2 string Copied
