String copying in c programming

This program copy string using library function strcpy, to copy string without using strcpy see source code below in which we have made our own function to copy string.

C program to copy a string

#include <stdio.h>
#include <string.h>
 
int main()
{
   char source[1000], destination[1000];
 
   printf("Input a string\n");
   gets(source);
 
   strcpy(destination, source);
 
   printf("Source string:      \"%s\"\n", source);
   printf("Destination string: \"%s\"\n", destination);
 
   return 0;
}
Output of program:
C program to copy string output

C program to copy string without using strcpy

We create our own function to copy string and do not use the library function strcpy.
#include <stdio.h>
#include <string.h>
 
void copy_string(char [], char []);
 
int main() {
   char s[1000], d[1000];
 
   printf("Input a string\n");
   gets(s);
 
   copy_string(d, s);
 
   printf("Source string:      \"%s\"\n", s);
   printf("Destination string: \"%s\"\n", d);
 
   return 0; 
}
 
void copy_string(char d[], char s[]) {
   int c = 0;
 
   while (s[c] != '\0') {
      d[c] = s[c];
      c++;
   }
   d[c] = '\0';
}

C program to copy a string using pointers

Function to copy string using pointers.
void copy_string(char *target, char *source) {
   while (*source) {
      *target = *source;
      source++;
      target++;
   }
   *target = '\0';
}

No comments:

Post a Comment