Extra 5% OFF Use Code: OL05
Free Shipping over ₹999

Copy string without using strcpy()

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:

  1. 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.
  2. User Input:
    • The program asks the user to enter a string and stores it in arr1.
    • The cin input will stop reading when it encounters whitespace (like a space or newline), so the user can enter a word without spaces.
  3. Copy the String:
    • A for loop is used to copy each character from arr1 to arr2.
    • 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 \0 to the end of arr2 to properly terminate the string.
  4. Display Both Strings:
    • The program prints the original string (arr1) and the copied string (arr2).

Example :

  1. The user enters the string “hello”.
    • arr1 = "hello"
  2. The for loop 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 \0 at the end of arr2.
  3. The output will be:

Output:

hello = Array 1 String
hello = Array 2 string Copied

    Leave a Reply

    Your email address will not be published.

    Need Help?