C Program to Write a String Copy Function

In this post, you will learn a program to write a string copy function. C programming language has many built-in string functions including the strcpy() function. The strcpy() function copy text from one string to another. To understand the working of string copy function, we write a program that copies text from one string to another.

This program is written using Dev-C++ compiler installed on a Windows 7 64-bit machine and it is intended for beginners of C programming.

Problem Definition

The program reads a string and then copy that string to another string and display the results.Each string is an array of characters with a null character at the end of the string. Make sure that the size of the string is same or greater than string 2 size, otherwise, there will be problem copying string 1 to string 2.

Start copying string character by character from string 1 to string 2, until we reach a null character.

Assign a null character to the string 2 when all characters of string 1 are copied successfully. This is because every string in C language must end with a ‘\0’.

For Example:-

Suppose the program reads “hello” to string 1, and then the starts copying string 1 to string 2 one character at a time until a null is encountered. See figure below.

String Copy Diagram
String Copy Diagram

Flowchart – Program to Write a String Copy Function

Flowchart - C Program to Write a String Copy Function
Flowchart – C Program to Write a String Copy Function

 

Program Code – String Copy Function

  #include <stdio.h>  #include <conio.h>      int main ()  {        char s1 [10];      char s2 [10];      int i;        void strcopy (char s2 [10], char s1 [10]);          /* Read the String 1 */          printf ("Enter String 1 :");      gets (s1);          /* Copy the String 1 to String 2 */          strcopy (s2, s1);          /* Print both the functions */              for (i=0; i<35; i++)      printf("_");printf("\n\n");        printf("String2=%s \n\nString1=%s\n",s2,s1);        for(i=0;i<35;i++)      printf("_");printf("\n\n");          system("PAUSE");      return 0;    }    void strcopy (char s2[10], char s1[10])  {        int i= 0;        while(s1[i] !='\0')      {            s2[i] = s1[i];          ++i;      }        s2[i]='\0';    }

Output

Output - C Program to Implement a String Copy Function
Output – C Program to Implement a String Copy Function
Advertisements