Table of Contents
In C, a string is internally an array of individual characters, with the last element being a null character, which is how the compiler knows when the string ends.
An important thing to know how to do is take one string and add it to another string. This is called concatenation.
C doesn't make it as easy as some other languages, but it's not too hard to do.
In this post, we'll learn how to concatenate strings in C.
How to Concatenate Strings in C
Let's first start by defining the two strings that we want to concatenate.
CLIKE#include <stdio.h>
int main()
{
char a[] = "Apple";
char b[] = "Banana";
return 0;
}
Now, the easiest way to concatenate strings in C is to use the strcat
function. This function is defined in the string.h
header file, so we need to include that.
CLIKE#include <stdio.h>
#include <string.h>
Now, we can use the strcat
function to concatenate the two strings.
CLIKEstrcat(a, b);
This will modify the first string, a
, and add the second string, b
, to the end of it.
Let's put it all together and print out the result.
CLIKE#include <stdio.h>
#include <string.h>
int main()
{
char a[] = "Apple";
char b[] = "Banana";
strcat(a, b);
printf("%s", a);
return 0;
}
BASHAppleBanana
Under the hood, the strcat
function is just looping through the first string, a
, and finding the null character at the end of it. Then, it starts adding the characters from the second string, b
, to the end of the first string.
Finally, it adds a null character to the end to indicate the end of the string.
Conclusion
In this post, we learned how to concatenate strings in C.
Simply use the strcat
function from the string.h
header file to concatenate two strings, while modifying the first string.
Thanks for reading!
- Managing PHP Dependencies with Composer
- Best Visual Studio Code Extensions for 2022
- How to deploy a MySQL Server using Docker
- How to deploy an Express app using Docker
- Learn how to use v-model with a custom Vue component
- How to Scrape the Web using Node.js and Puppeteer
- Getting Started with Handlebars.js
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Getting Started with React
- Setting Up a Local Web Server using Node.js
- Using Axios to Pull Data from a REST API
- Getting Started with Moon.js