C - String String Concatenating

Introduction

Concatenation is to append one string to the end of another.

strcat_s() function in string.h does the string concatenating.

strcat_s() requires three arguments:

  • the address of the string that is to be appended to,
  • the maximum length of the string that can be stored by the first argument, and
  • the address of the string that is to be appended to the first argument.

The function returns an integer error code as a value of type errno_t, which is an integer type that is compiler dependent.

char str1[50] = "To be, or not to be, ";
char str2[] = "that is the question.";
int retval = strcat_s(str1, sizeof(str1), str2);
if(retval)
  printf("There was an error joining the strings. Error code = %d",retval);
else
  printf("The combined strings:\n%s\n", str1);

The code above uses strcat_s() to append str2 to str1.

The operation copies str2 to the end of str1, overwriting the \0 in str1, then appending a final \0.

When everything works as it should, strcat_s() returns 0.

If str1 is not large enough or there is some other error, the return value will be nonzero.

strncat_s() concatenates part of one string to another.

This has an extra argument specifying the maximum number of characters to be concatenated. Here's how that works:

char str1[50] = "To be, or not to be, ";
char str2[] = "that is the question.";
int retval = strncat_s(str1, sizeof(str1), str2, 4);
if(retval)
  printf("There was an error joining the strings. Error code = %d",retval);
else
  printf("The combined strings:\n%s\n", str1);

Related Topics