Write a C program to copy one string to another using strcpy() library function. How to use strcpy() library function.
Example:
Input string1: Hello World!
Output string2: Hello World!
Required knowledge
Basic C programming, Loop, StringProgram to copy string without using strcpy()
/**
* C program to copy one string to another string without using strcpy()
*/
#include <stdio.h>
int main()
{
char text1[100], text2[100];
int i;
/* Reads the original string to be copied from user */
printf("Enter any string: ");
scanf("%s", &text1);
/* Copies text1 to text2 character by character */
i=0;
while(text1[i]!='\0')
{
text2[i] = text1[i];
i++;
}
//Makes sure that the string is NULL terminated
text2[i] = '\0';
printf("First string = %s\n", text1);
printf("Second string = %s\n", text2);
printf("Total characters copied = %d\n", i);
return 0;
}
Output
Enter any string: CodeforWin
First string = CodeforWin
Second string = CodeforWin
Total characters copied = 10
First string = CodeforWin
Second string = CodeforWin
Total characters copied = 10
Note: You can also use predefined string library function strcpy(dest-string, source-string) where the first parameter dest-string is the destination string to which the string is copied and source-string is the source string or original string. This function is present under string.h header file.
Program to copy string using strcpy()
/**
* C program to copy one string to another string using strcpy()
*/
#include <stdio.h>
#include <string.g>
int main()
{
char text1[100], text2[100];
/* Reads the original string to be copied from user */
printf("Enter any string: ");
scanf("%s", &text1);
/*
* Copies text1 to text2 using strcpy()
* Here first parameter of the function is destination string
* And second is the source string
*/
strcpy(text2, text1);
printf("First string = %s\n", text1);
printf("Second string = %s\n", text2);
return 0;
}
Output
Enter any string: CodeforWin
First string = CodeforWin
Second string = CodeforWin
First string = CodeforWin
Second string = CodeforWin
Happy coding ;)
You may also like
- String programming exercises index.
- C program to find length of a string.
- C program to convert uppercase string to lowercase string.
- C program to convert lowercase string to uppercase string
- C program to find reverse of a given string.
- C program to check whether a string is palindrome or not.
- C program to count number of vowels and consonants in a string.
- C program to find total number of words in a string.
- C program to find first occurrence of a character in string.
- C program to remove first occurrence of a character from string.
- C program to remove last occurrence of a character from string.
- C program to find frequency of each character in a string.