strcpy function in C Programming

4 years, 6 months ago C Programming

Today we will talk about a string assignment operator. But before that, we will solve a problem. The problem is very easy. We have to copy/assign one string to another.

Suppose str1 & str2 are two strings. We have to copy/assign str2 to str1. We may try this as follows:

#include <stdio.h>

int main()
{
 char str1[15] = "Bangladesh";
 char str2[15] = "Bangla";
 str1 = str2;
 puts(str1);
 return 0;
}

But C doesn’t permit such kind of string-assignment. The thing, you can do, is writing the following program:

#include <stdio.h>
#include <string.h>

int main()
{
 int i;
 char str1[15] = "Bangladesh";
 char str2[15] = "Bangla";
 puts(str1);
 for(i = 0; str2[i] != '\0'; i++){
 str1[i] = str2 [i];
 }
 str1[i] = '\0';
 puts(str1);
 return 0;
}

Output:

Bangladesh

Bangla

At first “Bangladesh” was in str1. But when we assign str2 to str1, only “Bangla” was in str1. Here we have used a loop. This process is very lengthy and not efficient too. There is a string library function defined in <string.h> header file. Actually I am saying about strcpy function. It’s a string-assignment operator. Its basic form is given below:

strcpy(str1, str2);

Here str1 & str2 are two parameters of strcpy function. It assigns str2 to str1. str1 is a string variable but str2 may be string variable or a string constant. Please consider the following program:

#include <stdio.h>
#include <string.h>

int main()
{
 char str1[15] = "Bangladesh";
 char str2[15] = "Bangla";
 puts(str1);
 strcpy(str1, str2);
 puts(str1);
 strcpy(str1, "Programming");
 puts(str1);
 return 0;
}

Output:

Bangladesh

Bangla

Programming

That’s all about strcpy function. For further help, please comment. Happy Coding!!!

Previous Next
Comments
Have you read the comment guideline?

Give me useful, constructive criticism. Spot a typo or an error? Let me know and I will correct it.