C Program to Copy String Without Using strcpy()
In this article, you’ll learn to copy string without using the library function strcpy().
You can use the strcpy() function to copy the content of one string to another but, this program copies the content of one string to another manually without using strcpy()
function.
Example: Copy String Manually Without Using strcpy()
#include <stdio.h>
int main()
{
char s1[100], s2[100], i;
printf("Enter string s1: ");
scanf("%s",s1);
for(i = 0; s1[i] != '\0'; ++i)
{
s2[i] = s1[i];
}
s2[i] = '\0';
printf("String s2: %s", s2);
return 0;
}
Output
Enter String s1: program String s2: program
This above program copies the content of string s1 to string s2 manually.
C program to copy a string without using strcpy()
the function:
#include <stdio.h>
int main() {
char str1[100], str2[100];
int i;
printf("Enter a string:\n");
gets(str1);
for (i = 0; str1[i] != '\0'; i++) {
str2[i] = str1[i];
}
str2[i] = '\0';
printf("Copied string: %s\n", str2);
return 0;
}
Explanation:
#include <stdio.h>
includes the standard input-output header file in our program.char str1[100], str2[100];
declares two character arraysstr1
andstr2
to store the original and copied strings respectively.int i;
declares an integer variablei
.- The
printf()
statement is used to display a message to the user to input a string and thegets()
function is used to input the string. - The
for
loop starting fromfor (i = 0; str1[i] != '\0'; i++)
copies each character of the stringstr1
tostr2
one by one until the end of the string is reached. - The statement
str2[i] = '\0';
adds the null character at the end of the copied string to indicate the end of the string. - The last
printf()
statement displays the copied string.
When we compile and run this program, it will prompt the user to input a string and then copy it without using the strcpy()
function. Finally, it will display the copied string.