C program to copy string without using strcpy() function
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
// C program to copy one string to other // without using in-built function #include <stdio.h> // Driver code int main() { // s1 is the source( input) string and // s2 is the destination string char s1[] = "w3wiki" , s2[100], i; // Print the string s1 printf ( "string s1 : %s\n" , s1); // Execute loop till null found for (i = 0; s1[i] != '\0' ; ++i) { // copying the characters by // character to str2 from str1 s2[i] = s1[i]; } s2[i] = '\0' ; // printing the destination string printf ( "String s2 : %s" , s2); return 0; } |
string s1 : w3wiki String s2 : w3wiki
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
// C program to copy one string to other // using pointers #include <stdio.h> #include <string.h> // Function to copy one string to // another string void CopyString( char * st1, char * st2) { int i = 0; for (i = 0; st1[i]!= '\0' ; i++) { st2[i] = st1[i]; } st2[i] = '\0' ; } // Driver code int main() { char str1[100] = "Beginner for Beginner" , str2[100]; CopyString(str1, str2); printf ( "\nString s1: %s" , str1); printf ( "\nString s2: %s" , str2); return 0; } |
String s1: Beginner for Beginner String s2: Beginner for Beginner
Contact Us