C Programming: strcat() Function

beginner
15 min

C Programming: strcat() Function

Welcome to our deep dive into the strcat() function in C programming! This function is a powerful tool for manipulating strings, and we'll cover its usage, understanding, and practical applications in this comprehensive guide. Let's get started!

What is strcat()? 💡

strcat() is a built-in C library function that stands for "string concatenation." It appends a source string to the end of a destination string.

Understanding strcat() 📝

The strcat() function requires two arguments:

  1. char* destination: This is the string that will have the source string appended.
  2. char* source: This is the string that will be appended to the destination string.

Syntax

c
char* strcat(char *destination, const char *source);

How does strcat() work? 🎯

  1. The function starts by finding the null character (\0) at the end of the destination string.
  2. It then moves the null character to the end of the destination string, creating space for the source string.
  3. The source string is then appended to the destination string, and the function returns the updated destination string.

Example 1 📝

Let's see a simple example of using strcat():

c
#include <stdio.h> #include <string.h> int main() { char str1[20] = "Hello, "; char str2[10] = "World!"; strcat(str1, str2); printf("%s", str1); // Output: "Hello, World!" return 0; }

Advanced Usage 💡

You can use strcat() in more complex scenarios too! Here's an example where we create a simple command-line program that concatenates two user-provided strings:

c
#include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char* argv[]) { if(argc < 3) { printf("Usage: %s string1 string2\n", argv[0]); return 1; } char* result = (char*)malloc((strlen(argv[1]) + strlen(argv[2]) + 1) * sizeof(char)); strcpy(result, argv[1]); strcat(result, " "); strcat(result, argv[2]); printf("%s\n", result); free(result); return 0; }

Save this code in a file named concat.c, and compile and run it using the command line:

sh
gcc concat.c -o concat ./concat Hello World

Quiz 🎯

Quick Quiz
Question 1 of 1

What does the `strcat()` function do in C programming?

Happy coding! Let's continue exploring the wonderful world of C programming! 🚀