![]() |
VOOZH | about |
The strncpy() function in C is a predefined function in the string.h library used to copy a specified number of characters from one string to another. To use this function, we must include the <string.h> header file in our program. It copies up to n characters from the source string to the destination string and works with char data types.
char *strncpy(char *dest, const char *src, size_t n);
The strncpy(dest, src, n) function takes three parameters:
The strncpy(dest, src, n) function returns a pointer to the destination string dest. If the length of src is less than n, the remainder of dest will be padded with null characters.
Input:
char src[] = "Hello, World!";
char dest[20];
Output:
Destination string: Hello //Copied first 5 characters from src to dest
The below examples demonstrates the usage of strncpy() in different scenarios in C language.
The below program demonstrates the basic usage of the strncpy() function to copy a specified number of characters from one string to another.
Destination string: Hello
Time Complexity: O(n), where n is the number of characters to be copied.
Auxiliary Space: O(1)
The below example demonstrates how we can use strncpy() to copy a fixed length of characters from a source string to a destination string, ensuring the destination string is properly null-terminated.
Custom copied string: Programming in
Time Complexity: O(n), where n is the number of characters to be copied.
Auxiliary Space: O(1)
The below example demonstrates how to use strncpy() to copy a fixed-length substring from the source string into the destination string.
Fixed-length substring: Moore
Time Complexity: O(n), where n is the number of characters to be copied.
Auxiliary Space: O(1)