STRNCPY()
this function copies a specified number of characters from one string to another.
char *strncpy(char *destination, char *source, int n);
#include <stdio.h>
#include <string.h>
int main() {
// Declare the source string
char source[] = "Hello, C Programming!";
// Declare a destination string with sufficient space
char destination[20];
// Use strncpy to copy 10 characters from source to destination
strncpy(destination, source, 10);
// Manually null-terminate the string, just in case
destination[10] = '\0';
// Print the result
printf("Copied string: %s\n", destination);
return 0;
}
* OUTPUT:
Copied string: Hello, C P
* makes a copy of a maximum n characters taken from the string pointed to by
source and stores them in the location pointed to by destination
- if source contains fewer characters than n, all of them are copied. the
finishing null character is only added to the copied string if this character
is in n range
char *result = strncpy(destination, source, num);
* result points to the destination string, with the first num characters of source
copied. If the source is shorter than num, the destination is padded with '\0'
Last updated