Implementation of strncat() in c

26 Sep 2022 Balmiki Mandal 0 C Programming

C Programming: How to Write Your Own strncat() Function

The implementation of strncat() in C is a function that appends the specified number of characters from the source string at the end of the destination string and returns a pointer to the destination string.

The strncat() function is declared in the <string.h> header file and its syntax is as follows:

C Programming
char *strncat(char *dest, const char *src, size_t n);

Parameters:

  • dest: A pointer to the null-terminated destination string.
  • src: A pointer to the null-terminated source string.
  • n: The number of characters to append from the source string.

Return value:

A pointer to the destination string.

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

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

  // Append the first 5 characters from the source string to the destination string.
  char *ptr = strncat(dest, src, 5);

  // Print the destination string.
  printf("%s\n", dest);

  return 0;
}

Output:

Hello, w!

implementation of strncat() in C typically works as follows:

  1. It finds the end of the destination string using the strlen() function.
  2. It copies the first n characters from the source string to the end of the destination string.
  3. It appends a null-terminator character to the end of the destination string.

Simple implementation of the strncat() function in C:

C Programming
char *strncat(char *dest, const char *src, size_t n) {
  char *ptr = dest + strlen(dest);

  while (n-- && *src != '\0') {
    *ptr++ = *src++;
  }

  *ptr = '\0';

  return dest;
}

 

The strncat() function is a useful function for appending strings together. It is particularly useful when you need to append a limited number of characters from the source string.

Further Reading:


Implementation of strncat() in C

add source string at the end of destination string

comparing two string using strcmp and strncmp

Design a function to copy to copy string into destination string using strcpy and strncpy

how to implement implementation of strncpy in c

Design a function to calculate the length of the string using strlen

pre defined string based function

Design a function using my_strcpy and using my_strchr we need to select given char in given string

 

Enroll Now:

C-Programming From Scratch to Advanced 2023-2024] "Start Supercharging Your Productivity!"

Contact Us:

  • For any inquiries, please email us at [info@electro4u.net].
  • Follow us on insta  [ electro4u_offical_ ] for updates and tips.

Note: If you encounter any issues or specific errors when running this program, please let me know and I'll be happy to help debug them!

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.