In this C program, we will learn about how to copy a given string. We first take a string as input from user using gets function and store it in a character array. Now, we have to copy all characters of input string to another string including null character. At last we have to print input string as well as copy string on screen.
We can either use strcpy function of string.h header file to copy string or write our own function to copy string using pointers.
C program to copy a string using strcpy function
To use strcpy function, we must include string.h header file in our program. Here is the declaration for strcpy() function.
- source is the pointer to the string to be copied.
- destination is the pointer to the string where the content is to be copied.
The strcpy() function copies the characters of source string into destination string, including null character. source must be a char pointer to a string terminated by a null character. After copying, it returns a pointer to destination.
#include <stdio.h> #include <string.h> int main(){ char inputString[100], copyString[100]; printf("Enter a string of length less than 100 \n"); gets(inputString); strcpy(copyString, inputString); printf("Input String: %s \n", inputString); printf("Copy String: %s", copyString); return 0; }Output
Enter a string of length less than 100 Tech Crash Course Input String: Tech Crash Course Copy String: Tech Crash Course
C program to copy string using pointers in a user defined function
In this program, we are using our own function stringCopy to copy string. It takes source and destination pointers as parameters and does input validation(neither source nor destination pointer should be NULL). Inside while loop, it copies characters one by one from source string to destination string till null character. After copying it returns a pointer to destination string.
#include <stdio.h> #include <string.h> char* stringCopy(char *destination, char *source); int main(){ char inputString[100], copyString[100]; printf("Enter a string \n"); gets(inputString); stringCopy(copyString, inputString); printf("Input String: %s \n", inputString); printf("Copy String: %s", copyString); return 0; } char* stringCopy(char *destination, char *source){ int index = 0; if(NULL == source || NULL == destination){ return NULL; } while(source[index] != '\0'){ destination[index] = source[index]; index++; } destination[index] = '\0'; return destination; }Output
Enter a string techcrashcourse.com Input String: techcrashcourse.com Copy String: techcrashcourse.com
Related Topics