String concatenation in C is the process of joining two or more strings into a single string. This involves taking characters from one string and appending them to the end of another string until the null terminator ('\0'
) of the first string is reached.
Implementation of String Concatenation Program
Here’s a simple implementation of a program that concatenates two strings in C:
Explanation of the Program
Header Files:
#include <stdio.h>
: This header file is included for input and output functions.
Function Definition:
void stringConcatenate(char *dest, const char *src)
: This function concatenates the source string to the destination string.- Parameters:
char *dest
: Pointer to the destination string, which will be modified to hold the concatenated result.const char *src
: Pointer to the source string to be appended.
Finding the End of the Destination String:
- The first
while
loop (while (*dest != '\0')
) moves thedest
pointer to the end of the current string by incrementing it until it reaches the null character.
- The first
Appending the Source String:
- The second
while
loop (while (*src != '\0')
) copies characters from the source string to the destination string. - Each character from
src
is copied to the current position indest
, and both pointers are incremented.
- The second
Null Terminator:
- After copying all characters from the source string, a null character is added to the end of the destination string to properly terminate it.
Main Function:
- Two character arrays,
str1
andstr2
, are declared to hold the input strings. - The user is prompted to enter both strings using
fgets
, which allows spaces in the input. - The
strcspn
function is used to remove any newline character from the input strings. - The
stringConcatenate
function is called to concatenatestr2
tostr1
. - Finally, the concatenated string is displayed.
- 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 two strings when prompted.
Example Input/Output
Input:
Output:
Conclusion
The string concatenation program in C demonstrates how to manually join two strings together. Understanding this process is essential for manipulating strings in C, especially since C does not provide built-in operators for string concatenation like higher-level languages. This program reinforces the concepts of pointers, character manipulation, and memory handling in C programming.