strcpy(): Copying of strings in C

#include <stdio.h>
#include <string.h>
int main(void){
char var1[20]="My First Name";
char var2[]="My Second Name ";
strcpy(var2,var1);
printf(var2);
return 0;
}
The output of above code is here
My First Name
We can use string function strcpy() to copy strings.
The second string is added to the first string.
strcpy(destination_string, source_string);
  • Source string is not affected
  • Destination string is replaced by source string.

Copy the string without using strcpy()

Note : \0 is used to terminate a string.
#include <stdio.h>

int main(void){
  int i;
  char str1[]="welcome to c program";
  char str2[100];

 for(i=0;str1[i]!='\0';i++){
  str2[i]=str1[i];
 }
 str2[i]='\0'; // terminate the string
 printf("\n  %s ", str2);
 return 0;
}
Output is here
welcome to c program

Example: Copying User Input Strings

#include <stdio.h>
#include <string.h>
int main(void) {
    char src[100], dest[100];
    printf("Enter a source string: ");
    fgets(src, sizeof(src), stdin);  // Safe input
    strcpy(dest, src);
    printf("Copied string: %s\n", dest);
    return 0;
}
Output:
Enter a source string: Welcome to plus2net
Copied string: Welcome to plus2net



plus2net.com






We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2025   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer