strncat(): Concatenation of part of string

#include <stdio.h>
#include <string.h>
int main(void){
char var1[20]="plus2net";
char var2[]="welcome to ";
strncat(var2,var1,5);
printf(var2);
return 0;
}
The output of above code is here
welcome to plus2
We can use string function strncat() to concatenate part of strings.
The part of second string is added at the end of the first string.
strncat(destination_string, source_string,n);
  • Source string is not affected
  • Part of the Source string is added at the end of the destination string.

Example: Custom Implementation of strncat()

The manual strncat() shows how to append a limited number of characters from the source to the destination.
#include <stdio.h>
#include <string.h>
char* custom_strncat(char* dest, const char* src, size_t n) {
    char* ptr = dest + strlen(dest);  // Move pointer to the end of dest
    while (*src && n--) {
        *ptr++ = *src++;  // Append characters
    }
    *ptr = '\0';  // Null-terminate dest
    return dest;
}

int main() {
    char dest[20] = "Hello, ";
    char src[] = "World!";
    custom_strncat(dest, src, 3);  // Concatenate first 3 characters of src
    printf("Result: %s\n", dest);  // Output: Hello, Wor
    return 0;
}
Output
Result: Hello, Wor

Example: Ensuring Enough Space in Destination String

Demonstrates checking whether the destination string has enough space before concatenation, preventing overflow.
#include <stdio.h>
#include <string.h>

int main() {
    char dest[20] = "Plus2Net";
    char src[] = "C Tutorial";

    // Ensure enough space in dest before concatenating
    if (sizeof(dest) - strlen(dest) - 1 >= strlen(src)) {
        strncat(dest, src, 5);  // Concatenate first 5 characters
        printf("Concatenated string: %s\n", dest);  // Output: Plus2NetC Tut
    } else {
        printf("Not enough space in destination string!\n");
    }
    return 0;
}
Output
Concatenated string: Plus2NetC Tut



plus2net.com






We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2025   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer