C program to copy one string to another string without using strcpy()


Generally, Strings in C programming are terminated with null character i.e., ‘\0’. This program accomplishes the given task i.e copy one string to another string without using strcpy() by copying each and every character of the input string into an array until it encounters ‘\0’ at the end of the input string and then copied array is padded with ‘\0’ to make that array as a string.

 C program to copy one string to another string without using strcpy()


Source code:

#include<stdio.h>
void string_copy(char [], char []); /* function prototype */

int main()
{
	char a[100];  /*** source string ***/
	char b[100];  /*** destination string ***/
	printf("\n Input source string : ");
	scanf("%[^\n]",a);  /* read input source string *///Step 1
	string_copy(b,a);  /* function call */            //Step 2
	printf("\n Destination string : %s\n",b);
	return 0;
}
/*** function definition ***/
void string_copy(char d[], char s[])
{
	int i = 0;
	printf("\n Source string : %s\n",s);
	for (i = 0; s[i] != '\0'; i++)   /* copying the string *///Step 3
	     d[i] = s[i];
	d[i] = s[i]; /* Copy NUL character to destination string */  //Step 4
}


edit-code-image

Sample test cases:

1.  Input source string : hello
    Source string : hello
    Destination string : hello

2.  Input source string : topoint.in
    Source string : topoint.in
    Destination string : topoint.in
 

Explanation:

Step 1 : Enter the first input string. This string is read using Scanf function.
Step 2 : The String_Copy function is called where the string entered is copied into another string without using Strcpy().
Step 3 : Make use of a for loop to iterate through all the characters in string and copy each of them into the new string
Step 4 : Copy the last null character into the new string as this indicates end of the string in C Language.
Remember String is an array of characters!

More about C Programming : C Programming
Explore C Programs : C Programs