Explain String functions
String-Handling Functions
C library supports a large number of string-handling functions that can be used to carry out many of the string manipulations.
Most commonly used string functions are :
strcat( ) – concatenates two strings
strcmp( ) – compares two strings
strcpy – copies one string into another
strlen – finds the length of a string
These functions are defined in string.h header file.
strcat() function
The strcat function joins two strings together.
It takes the following form :
strcat(string1,string2);
Where string1 & string two are character arrays.
When the strcat function is excuted, string two is appended to string1.
It does so by removing the null character at the end of string1 and placing string2 from there.
The string at string2 remains unchanged.
Size of string1 should be enough to accommodate the final string.
strcat function may also append a string constant to a string variable.
strcmp() function
The strcmp compares two functions identified by the arguments and has a value of 0 if they are equal.
If they are not, it has numeric difference between the first nonmatching characters in the strings.
It takes the form :
strcmp(string1,string2);
string1 and string2 may be string variables or string constants.
strcpy function
strcpy copies one string into another.
It takes the form :
strcpy(string1,string2);
It assigns the contents of string2 to string1.
string2 may be a character array variable or a string constant.
strlen function
This function counts and returns the number of characters in a string.
It takes the form :
n=strlen(string);
Where n is an integer variable, which receives the value of the length of the string.
The argument may be a string constant.
The counting ends at the first null character.
strncpy – it copies the left-most n characters of the sourse string to the target string variable.
This is a three parameter function & has the following form :
strncpy(string1,string2,n);
strncmp – this fuction has three parameter and has the following
form :
strncmp(string1,string2,n);
This compares the left-most n characters of string1 to string2
and returns :
O if they are equal.
Negative number, if string1 is less than string2.
Positive number, otherwise.
strncat -
This function concatenates the left-most n characters of second string to the end of first string.
It takes the following form :
strncat(string1,string2,n);
strstr –
It is a two-parameter function that can be used to locate a sub-string in a string.
It takes the form :
strstr(string1,string2);
The function strstr searches the string1 to see whether the string2 is contained in string1.
if yes function returns the position of the first occurrence of the sub-string. Otherwise, it returns a NULL pointer.