The string copy program in C is used to copy the contents of one string (source) into another string (destination). This involves iterating through each character of the source string and assigning it to the destination string until the null character ('\0'
) is encountered, indicating the end of the string.
Implementation of String Copy Program
Here’s a simple implementation of a program that copies one string to another in C:
Explanation of the Program
Header Files:
#include <stdio.h>
: This header file is required for input and output functions.
Function Definition:
void stringCopy(char *dest, const char *src)
: This function copies the source string to the destination string.- Parameters:
char *dest
: Pointer to the destination string where the source string will be copied.const char *src
: Pointer to the source string that will be copied.
While Loop:
- The loop continues until the null character of the source string (
*src != '\0'
) is reached. - Inside the loop:
- Each character from the source string (
*src
) is copied to the destination string (*dest
). - The pointers
dest
andsrc
are incremented to move to the next character.
- Each character from the source string (
- The loop continues until the null character of the source string (
Adding Null Character:
- After copying all characters, a null character is added to the end of the destination string to properly terminate it.
Main Function:
- Two character arrays,
source
anddestination
, are declared to hold the strings. - The user is prompted to enter a string, which is read using
fgets
to include spaces. - The
strcspn
function is used to remove any newline character that might be present. - The
stringCopy
function is called to copy the source string to the destination string. - Finally, the copied string is displayed to the user.
- Two character arrays,
How to Run the Program
Compile the Code: Use a C compiler like
gcc
to compile the code.Execute the Program:
Input Data: Enter a string when prompted.
Example Input/Output
Input:
Output:
Conclusion
The string copy program in C demonstrates how to manually copy strings without using the built-in strcpy
function from the C standard library. This understanding of how strings work, including their termination and character manipulation, is crucial for working with strings in C programming. It also helps to grasp concepts like pointers and memory management effectively.