C strncat() function
C strncat() function - concatenate a string with part of another
Syntax:
char *strncat(char *string1, const char *string2, size_t count);
C strncat() function (string.h): The strncat() function is used to append the first count characters of string2 to string1 and ends the resulting string with a null character (\0).
Parameters:
Name | Description | Required /Optional |
---|---|---|
string1 | Null-terminated destination string. | Required |
string2 | Null-terminated source string. | Required |
count | Number of characters to append. | Required |
Return value from strncat()
Returns a pointer to the destination string. No return value is reserved to indicate an error.
Example: strncat() function
In the folowing program strncat() appends only the specified number of characters in the second string to the first.
#include <stdio.h>
#include <string.h>
#define SIZE 40
int main(void)
{
char string1[SIZE] = "C";
char * ptr;
/* Reset string1 to contain just the string "computer" again */
memset( string1, '\0', sizeof( string1 ));
ptr = strcpy(string1, "computer" );
/* Call strncat with string1 and " program" */
ptr = strncat( string1, " program", 3 );
printf( "strncat: string1 = \"%s\"\n", string1 );
}
Output:
strncat: string1 = "computer pr"
Example: Difference between strcat() and strncat()
The following example demonstrates the difference between strncat() and strcat(). The strncat() function appends only the specified number of characters in the second string to the first whereas the strcat() function appends the entire second string to the first.
#include <stdio.h>
#include <string.h>
#define SIZE 40
int main(void)
{
char string1[SIZE] = "C";
char * ptr;
/* Call strcat with buffer1 and " program" */
ptr = strcat( string1, " program" );
printf( "strcat : string1 = \"%s\"\n", string1 );
/* Reset string1 to contain just the string "computer" again */
memset( string1, '\0', sizeof( string1 ));
ptr = strcpy(string1, "C" );
/* Call strncat with string1 and " program" */
ptr = strncat( string1, " program", 3 );
printf( "\nstrncat: string1 = \"%s\"\n", string1 );
}
Output:
strcat : string1 = "C program" strncat: string1 = "C pr"
C Programming Code Editor:
Previous C Programming: C strcat()
Next C Programming: C strchr()
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics