A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.tutorialspoint.com/c_standard_library/c_function_strncat.htm below:

C library - strncat() function

C library - strncat() function

The C library strncat() function takes three variable as parameters which appends the string pointed to by src to the end of the string pointed to by dest up to n characters long.

Below are some key points that highlight its importance −

Syntax

Following is the syntax of the C library function strncat()

char *strncat(char *dest, const char *src, size_t n)
Parameters

This function accepts the following parameter −

Return Value

This function returns a pointer to the resulting string dest.

Example 1

Following is the basic C library program that demonstrates the usage of strncat() function.

#include <stdio.h>
#include <string.h>

int main () {
   char src[50], dest[50];

   strcpy(src,  "This is source");
   strcpy(dest, "This is destination");

   strncat(dest, src, 15);

   printf("Final destination string : |%s|", dest);
   
   return(0);
}
Output

The above code produces the following result −

Final destination string : |This is destinationThis is source|
Example 2

In this example, we utilize the concatenation of fixed-length substring from the source string to the destination string using strncat().

#include <stdio.h>
#include <string.h>

int main() {
   char dest[20] = "Hello, ";
   char src[] = "Beautiful World!";

   // Append "World"
   strncat(dest, src + 10, 5); 

   printf("Concatenated substring: %s\n", dest);
   return 0;
}
Output

After executing the above code, we get the following result −

Concatenated substring: Hello, World
Example 3

Below the program demonstrates the source string to the destination string by ensuring a fixed length.

#include <stdio.h>
#include <string.h>

void customStrncat(char* dest, const char* src, size_t n) {
   size_t dest_len = strlen(dest);
   size_t i;

   for (i = 0; i < n && src[i] != '\0'; i++) {
       dest[dest_len + i] = src[i];
   }
   
   // Null-terminate the result
   dest[dest_len + i] = '\0'; 
}

int main() {
   char dest[20] = "Hello, ";
   char src[] = "World!";

   // Append "World"
   customStrncat(dest, src, 5); 

   printf("Custom concatenated string: %s\n", dest);

   return 0;
}
Output

On execution of above code, we get the following result −

Custom concatenated string: Hello, World

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4