C++ cstring strncat() Function



The C++ strncat() function is used to concatenate two strings.

It is similar to strcat() but the main difference is it only concatenate certain amount of character of two string. This function is defined in cstring header file.

We can make a single string out of two strings using the strncat() function. This function need three arguments, first string is that where the content is to be concatenated, second string is the source of data to be concatenated and third is the number of characters to be concatenated.

Syntax

Following is the syntax of the strncat() function −

char *strncat(char *string1, const char *string2, size_t num);

Parameters

This function returns the following the parameters −

  • string1 - Pointer to the destination array where the content is to be concatenated.

  • string2 - Pointer to the source of data to be concatenated.

  • num - Number of characters to concatenate.

Return Value

This function returns a single string which is the concatenated string of the destination and source strings.

Example 1

Let us understand how to use the strncat() function with the help of an example.

In this example, let's try to concatenate two strings using the strncat() function. For this, we will create two strings, one source string and one destination string. We will then concatenate the source string to the destination string using the strncat() function. and also we will concatenate only 5 characters of the source string to the destination string.

#include <iostream>
#include <cstring>

using namespace std;

int main() {
    char source[] = "Ayanokoji";
    char destination[100] = "Hello,";

    // Concatenating the source string to destination string
    strncat(destination, source, 5);

    cout << "Source: " << source << endl;
    cout << "Destination: " << destination << endl;

    return 0;
}

Output

When you run the program, the output will be:

Source: Hello,
Destination: Hello,Ayano

Example 2

Now we will just try to concatenate the string based on the condition. If the string contain letter 'a' then we will concatenate 5 characters of the string to the result string. If the string does not contain letter 'a' then we will move to the next string.

#include <iostream>
#include <cstring>

using namespace std;

bool hasA(char *str) {
    for (int i = 0; str[i] != '\0'; i++) {
        if (str[i] == 'a') {
            return true;
        }
    }
    return false;
}

int main() {
    char str1[] = "Ichigo";
    char str2[] = "Astha";
    char str3[] = "Ayanokoji";
    char result[100] = "";
    if(hasA(str1)) {
        strncat(result, str1, 5);
    }
    if(hasA(str2)) {
        strncat(result, str2, 5);
    }
    if(hasA(str3)) {
        strncat(result, str3, 5);
    }

    cout << "Result: " << result << endl;
    return 0;
}

Output

When you run the program, the output will be:

Result: AsthaAyano
Advertisements
close