String Manipulation Functions
It is known that a string can be represented as a one dimensional character type array. Each character in the string represents one array element.
The functions of strings require the ‘string.h’ header file to be included in the program.
Given below are library functions of strings in C programming.
- strlen (string length)
- strcpy(string copy)
- strcat(string concatenating)
- strcmp(string comparision)
strcpy(string copy)
strcpy takes two arguments: the destination string, the source string and copies source string into the destination string.
One of the uses for strcpy is reassigning values to string variables defined as char arrays.
To copy str2 to str1 (order resembles assignment):
strcpy (str1, str2);
str1 = str2; /* Will NOT work!! */
/*str1 = str2; just makes str1 now contain the pointer to str2. Remember that the name of an array is essentially a constant pointer to the first element of the array.*/
strcat (string concatenating)
'strcat' function concatenates a copy of string 1 to string 2 and terminates string 1 with a null.
The null terminator originally ending in string 1 is overwritten by the first character of string 2
To add (concatenate) str2 to the end of str1:
strcat (str1, str2); It returns the value of str1 with str2 added to the end.
strcmp (string comparison)
'strcmp' function compares two strings and returns an integer based on their comparison.
int strcmp(char const *sl, char const *s2); (it returns the values as given below.)
Value
|
Meaning
|
Less than zero
|
string 1 is less than string 2
|
zero
|
strings are equal
|
Greater than zero
|
string 1 is greater than string 2
|