Unlike single character constants
a string constant cannot be assigned directly with a string variable nor
compared with an another string.
String functions whose header file is <string.h> have
to be used to carry out operation such as comparision, concatenation (combining
two strings), assignment operators etc. Some functions are listed below.
strcpy():- This function copies the contents of source string
into destination string. Its syntax is
strcpy(destination
string, source string);
Example:
char sd[10], ss[10]={ “Hi welcome”};
strcpy(sd,ss);
cout<<sd;
Output:
Hi welcome
Thus sd=ss; is invalid statement as arithmetic operation can’t
be used two string variable.
strlen():- This function provides the length of the string
excluding null character.
Example:
char ss[10]={ “Welcome”};
int a= strlen(ss);
cout<<a;
Output:
7
The function strlen() counts no of
characters used in a string by ignoring null character while the operator
sizeof() counts total space allocated if the size is specified with the array
name or it counts no of characters including the null characters.
strlen() needs a header file because
it is a function whereas sizeof() does not require a header file because it is
an operator.
strcat():- This function concatenates(combines) the given
strings. Its syntax is
strcat(s1,s2);
It combines the string s1 with s2 and stores the resultant
string with s1.
Example:
char s1[10]= “Kota”;
char s2[10]= “Junction”;
strcat(s1,s2);
cout<<s1;
Output:
KotaJunction
strcmp():- It is a
function which compares two strings and provides the difference in integer
form.
Syntax:
strcmp(s1, s2);
if s1>s2 then it returns +ve
value.
if s1<s2 then it returns -ve
value.
if s1=s2 then it returns zero.
Example:
1.
s1= “BAT”;
s2= “CAT”;
strcmp(s1,s2)=-1
2.
s1= “ARUN”;
s2= “arun”;
strcmp(s1,s2)=-32
3.
s1= “Nirmal”;
s2= “Niranjan”;
strcmpi(s1,s2)=12
This function is case sensitive i.e. it treats uppercase and
lower case of same letter as different. The function strcmpi() can be use to
treat the lowercase and uppercase of a letter as identical.
Example:
s1= “ARUN”;
s2= “arun”;
strcmpi(s1,s2)=0