How to append characters from a string to another string in C++:
In this post, we will learn how to append characters from a string to another string in C++. We will use cstring for this. cstring provides a couple of useful methods those can be used with c-type strings, i.e. character array.
strncat is the method used to append characters from a character array to another character array.
Definition:
strncat is defined as like below:
char * strncat ( char * dest, const char * src, size_t num );
It appends the first num characters from src to dest and adds a terminating null-character.
Here,
- dest is the pointer to the destination array.
- src is the source string.
- num is the number of characters to append.
It returns the dest.
Example of strncat:
Let’s take a look at the below example:
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char firstArr[20] = "abcd efg";
char secondArr[20] = "hijk lmnop";
strncat(firstArr, secondArr, 4);
cout << firstArr << endl;
return 0;
}
It will print:
abcd efghijk