The header file <string.h> contains many more string manipulation functions. They might be useful in certain situations.
In addition to the function strcpy() that copies one string to another, we have another method strncpy() that copies only the left-most n characters of the source string to the target string variable. This is a three-parameter function and is invoked as follows :
This statement copies the first 4 characters of the source string str2 into the target string str1. Since the first 4 characters may not include the terminating null character, we have to place it explicitly in the 5th position of str2 as shown below :
str1 = '\0';
Now, the string str1 contains a proper string.
A variation of the function strcmp is the function strncmp(). This function has three parameters as illustrated in the function call below :
this compares the left-most n characters of str1 to str2 and returns.
This is another concatenation function that takes three parameters as shown below :
This call will concatenate the left-most n characters of str2 to the end of str1. Example :
After strncat(str1,str2,4); execution :
It is a two-parameter functions that can be used to locate a sub-string is a string. This takes the forms :
The function strstr() searches the string str1 to see whether the string str2 is contained in str1. If yes, the function returns the position of the first occurrence of the sub-string. Otherwise, it returns a NULL pointer. Example :
if(strstr(str1,str2) == NULL) printf("substring is not found"); else printf("str2 is a substring of str1");
We also have methods to determine the existence of a character in a string. The function call
will locate the first occurrence of the character 'a' and the call
will locate the last occurrence of the character 'a' in the string str1.