You are here

C copy string program

C copy string program: This program copy a string using library function strcpy, C program to copy a string without strcpy.

String copy C program

  1. #include <stdio.h>
  2. #include <string.h>
  3.  
  4. int main()
  5. {
  6.    char source[1000], destination[1000];
  7.  
  8.    printf("Input a string\n");
  9.    gets(source);
  10.  
  11.    strcpy(destination, source);
  12.  
  13.    printf("Source string: %s\n", source);
  14.    printf("Destination string: %s\n", destination);
  15.  
  16.    return 0;
  17. }

Output of program:
C program to copy a string output

Copy string in C without using strcpy

  1. #include <stdio.h>
  2.  
  3. int main()
  4. {
  5.   int c = 0;
  6.   char s[1000], d[1000] = "What can I say about my programming skills?";
  7.  
  8.   printf("Before copying, the string: %s\n", d);
  9.  
  10.   printf("Input a string to copy\n");
  11.   gets(s);
  12.  
  13.   while (s[c] != '\0') {
  14.     d[c] = s[c];
  15.     c++;
  16.   }
  17.  
  18.   d[c] = '\0';
  19.  
  20.   printf("After copying, the string: %s\n", d);
  21.  
  22.   return 0;
  23. }

Output of the program:

  1. Before copying, the string: What can I say about my programming skills?
  2. Input a string to copy
  3. My programming skills are improving.            
  4. After copying, the string: My programming skills are improving.

Creating a function to copy a string

  1. #include <stdio.h>
  2.  
  3. void copy_string(char [], char []);
  4.  
  5. int main() {
  6.   char s[1000], d[1000];
  7.    
  8.   printf("Input a string\n");
  9.   gets(s);
  10.  
  11.   copy_string(d, s);
  12.   printf("The string: %s\n", d);
  13.  
  14.   return 0;
  15. }
  16.  
  17. void copy_string(char d[], char s[]) {
  18.   int c = 0;
  19.    
  20.   while (s[c] != '\0') {
  21.     d[c] = s[c];
  22.     c++;
  23.   }
  24.   d[c] = '\0';
  25. }

C program to copy a string using pointers

Function to copy a string using pointers.

  1. void copy_string(char *target, char *source) {
  2.    while (*source) {
  3.       *target = *source;
  4.       source++;
  5.       target++;
  6.    }
  7.    *target = '\0';
  8. }