Program to Copy strings in C
Written by
Copy string in C
We shall learn different techniques in order to copy strings in C. Generally they are used when you need to work on the original string while also maintaining a copy for operational purpose or backup/recovery purpose.
APPROACH 1: Using strcpy() from string.h
- We use the built in function from string.h header file – strcpy() for performing string copy operation.
- Syntax: strcpy( destination_string, source_string);
- The first string mentioned is destination and the second is the source from where data is copied.
#include<stdio.h>
#include<string.h>
int main()
{
char *source, dest[50];
int size = 50;
printf("Enter the source string:\n");
source = (char*)malloc(size);
getline(&source, &size, stdin);
strcpy(dest, source); //performing string copy
printf("The Destination string after string copy is: %s\n", dest);
return 0;
}
Output:
Enter the source string:
how are you ?
The Destination string after string copy is: how are you ?
APPROACH 2: Using user-defined function to copy strings
- A user defined function string_copy is defined to copy the source strung’s content to destination string.
- We traverse the array character by character and assign the ith character to ith position at dest till null character is encountered in source string.
#include<stdio.h>
#include<string.h>
void string_copy(char dest[], char source[])
{
int i;
for( i=0; source[i]!='\0'; i++)
{
dest[i] = source[i];
}
dest[i] = '\0'; //appending null character to mark end of string
}
int main()
{
char *source, dest[50];
int size = 50, length, bytes_read;
printf("Enter the source string:\n");
source = (char*)malloc(size);
getline(&source, &size, stdin);
string_copy(dest, source); //fucntion call to string copy
printf("The Destination string after string copy is: %s\n", dest);
return 0;
}
Output:
Enter the source string:
how are you ?
The Destination string after string copy is: how are you ?
APPROACH 3: Using pointers and functions to copy strings
The technique is same as above, however we use pointers along with it.
#include<stdio.h>
#include<string.h>
void string_copy(char *dest, char *source)
{
while (*source)
{
*dest = *source;
source++;
dest++;
}
*dest = '\0'; //appending null character to mark end of string
}
int main()
{
char *source, dest[50];
int size = 50;
printf("Enter the source string:\n");
source = (char*)malloc(size);
getline(&source, &size, stdin);
string_copy(dest, source); //fucntion call to string copy
printf("The Destination string after string copy is: %s\n", dest);
return 0;
}
Output:
Enter the source string:
how are you ?
The Destination string after string copy is: how are you ?
We have now seen various methods to copy strings in C.