String copy in C

Created with Sketch.

 

String copy in C

C program to copy a string using library function strcpy and without using strcpy.

String copy C program

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

int main()
{
char source[1000], destination[1000];

printf(“Input a string\n);
gets(source);

strcpy(destination, source);

printf(“Source string: %s\n, source);
printf(“Destination string: %s\n, destination);

return 0;
}

Output of program:
C program to copy a string output

Copy string in C without using strcpy

#include <stdio.h>

int main()
{
int c = 0;
char s[1000], d[1000] = “What can I say about my programming skills?”;

printf(“Before copying, the string: %s\n, d);

printf(“Input a string to copy\n);
gets(s);

while (s[c] != \0) {
d[c] = s[c];
c++;
}

d[c] = \0;

printf(“After copying, the string: %s\n, d);

return 0;
}

Output of the program:

Before copying, the string: What can I say about my programming skills?
Input a string to copy
My programming skills are improving.
After copying, the string: My programming skills are improving.

Creating a function to copy a string

#include <stdio.h>

void copy_string(char [], char []);

int main() {
char s[1000], d[1000];

printf(“Input a string\n);
gets(s);

copy_string(d, s);
printf(“The string: %s\n, d);

return 0;
}

void copy_string(char d[], char s[]) {
int c = 0;

while (s[c] != \0) {
d[c] = s[c];
c++;
}
d[c] = \0;
}

C program to copy a string using pointers

Function to copy a string using pointers.

void copy_string(char *target, char *source) {
while (*source) {
*target = *source;
source++;
target++;
}
*target = \0;
}

Leave a Reply

Your email address will not be published. Required fields are marked *