C library provides functions to compare strings, copy a string and for other string manipulations. Below is a list of the string manipulation functions and their description. All these functions are defined in the header file string.h, in the C library.
Let’s look at the string copy function which is strcpy. The prototype of this function is
char *strcpy( char *s1, const char *s2 )
Here the first argument is a pointer to a character array or string s1 whereas the second argument is a pointer to a string s2. The string s2 is copied to string s1 and a pointer to that resultant string is returned. The string s2 remains the same. We can describe the string s1 as the destination string and s2 as the source string. As the source remains the same during the execution of strcpy and other string functions, the const keyword is used before the name of source string. The const keyword prevents any change in the source string (i.e. s2). If we want to copy a number of characters of a string instead of the entire string, the function strncpy is employed. The function strncpy has arguments a pointer to destination strings (s1), a pointer to source string (s2) . The third argument is int n. Here n is the number of characters which we want to copy from s2 into s1. Here s1 must be large enough to copy the n number of characters.
The next function is strcat (string concatenation). This function concatenates (joins) two strings. For example, in a string, we have first name of a student, followed by another string, the last name of the student is found. We can concatenate these two strings to get a string, which holds the first and the last name of the student. For this purpose, we use the strcat function. The prototype of this function is
char *strcat( char *s1, const char *s2 )
This function writes the string s2 (source) at the end of the string s1(destination). The characters of s1 are not overwritten. We can concatenate a number of characters of s2 to s1 by using the function strncat. Here we provide the function three arguments, a character pointer to s1, a character pointer to s2 while third argument is the number of characters to be concatenated. The prototype of this function is written as
char *strncat( char *s1, const char *s2, size_t n )
/*Program to display the operation
of the strcpy() and strncpy()*/
Following is the output of the program.