C Tutorial
This program is used to copy one string into the another string variable and prints copied variable value and length of the copied string.
#include<stdio.h> void main() { char string1[50], string2[50]; int i; printf("Enter String\n"); scanf("%s", string1); for(i=0;string1[i] != '\0'; i++) { string2[i] = string1[i]; } string2[i] = '\0'; printf("\nCopied String 'String2': %s\n", string2); printf("Copied String Length: %d", i); }Output:
$ cc copy-string.c $ ./a.out Enter String c-programming Copied String 'String2': c-programming Copied String Length: 13
In this C program, creating the user defined function strcopy using c pointers to copy a string from one array variable to aother one.
#include<stdio.h> #include<string.h> void strcopy(char *source, char *destination) { while(*source) { *destination = *source; source++; destination++; } } void main() { char str1[] = "testing codingpointer.com"; char str2[30]; strcopy(str1, str2); printf("\n%s", str2); }
Output:
$ cc string-copy.c $ ./a.out testing codingpointer.com[
Above program can be converted into single one line statement to copy a string to another string array variable.
#include<stdio.h> #include<string.h> void strcopy(char *source, char *destination) { while(*destination++ = *source++); } void main() { char str1[] = "testing codingpointer.com"; char str2[30]; strcopy(str1, str2); printf("\n%s", str2); }
Output:
$ cc string-copy.c $ ./a.out testing codingpointer.com[
C Tutorial
Privacy Policy | Copyright2020 - All Rights Reserved. | Contact us | Report website issues in Github | Facebook page | Google+ page