In this source code example, we will see how to use the strcat() function in C programming with an example.
strcat() Function Overview
The strcat() function in C is a standard library function that concatenates two strings and returns the concatenated string. The destination string should be large enough to store the concatenated result.
Key Points:
- Located in the <string.h> header file.
- It appends the source string at the end of the destination string.
- The destination string must be large enough to hold the result. Otherwise, undefined behavior occurs.
Source Code Example
#include <stdio.h> #include <string.h> int main() { char dest[50] = "Hello, "; char src[] = "world!"; // Using strcat to concatenate src onto dest strcat(dest, src); printf("%s\n", dest); // Adding more to the string strcat(dest, " Have a good day."); printf("%s\n", dest); return 0; }
Output
Hello, world! Hello, world! Have a good day.
Explanation
1. We start with a dest string containing "Hello, " and a src string with "world!".
2. With strcat(), we append the src string to the dest string, making it "Hello, world!".
3. We add another string, " Have a good day.", to the dest string using strcat(), showcasing its ability to continuously concatenate strings.
Comments
Post a Comment