strcpy is a C standard library function that copies a string from one location to another. It is defined in the string.h header file. We can use the inbuilt strcpy() function to copy one string to another but here, this program copies the content of one string to another manually without using strcpy() function.
Methods to Copy String without using strcpy()
There are two methods to print String without using the strcpy() function as mentioned below:
- Using for loop
- Using Pointers
1. Using for loop
Here we are giving one string in input and then with the help of for loop, we transfer the content of the first array to the second array.
Error: If the destination string length is less than the source string, the entire string value won’t be copied into the destination string. For example, consider the destination string length is 20 and the source string length is 30. Then, only 20 characters from the source string will be copied into the destination, and the remaining 10 characters will be truncated.
Below is the C program to copy string without using strcpy() function:
C
#include <stdio.h>
int main()
{
char s1[] = "GeeksforGeeks" , s2[100], i;
printf ( "string s1 : %s\n" , s1);
for (i = 0; s1[i] != '\0' ; ++i) {
s2[i] = s1[i];
}
s2[i] = '\0' ;
printf ( "String s2 : %s" , s2);
return 0;
}
|
Outputstring s1 : GeeksforGeeks
String s2 : GeeksforGeeks
The complexity of the above method
Time Complexity: O(n)
Auxiliary Space: O(n), The extra space is used to store the copied string.
2. Using Pointers
Below is the C program to copy strings using pointers:
C
#include <stdio.h>
#include <string.h>
void CopyString( char * st1, char * st2)
{
int i = 0;
for (i = 0; st1[i]!= '\0' ; i++)
{
st2[i] = st1[i];
}
st2[i] = '\0' ;
}
int main()
{
char str1[100] = "Geeks for Geeks" , str2[100];
CopyString(str1, str2);
printf ( "\nString s1: %s" , str1);
printf ( "\nString s2: %s" , str2);
return 0;
}
|
OutputString s1: Geeks for Geeks
String s2: Geeks for Geeks