String Functions
The string functions can analyze and transform null terminated strings. In order to manipulate null terminated strings header file <cstring> is included in the program. This header file provides the same functionality as string.h in C. Some of the commonly used string functions are: -
Here is a program which illustrates the working of string functions.
#include<iostream>
#include<cstring>
using namespace std;
int main ()
{
int l;
char name[40]=" Tom is a good boy";
char name1[40]="Mary is a good girl";
char stri[40];
l=strlen(name);
cout << "The lenght of the string 1 is : " << l << endl;
if(strstr(name,"good"))
{
cout << "Substring good appears in string 1 " << endl;
}
if(strchr(name1,'M'))
{
cout << "Character M appears in sting 1 " << endl;
}
if(strcmp(name,name1)>0)
{
cout << "String 2 appears after string" << endl;
}
strcpy(stri,name1);
cout << "The copied string : " << stri << endl;
strncat(stri,name,4);
cout << " The modified string : " << stri << endl;
if(strncmp(stri,name1,3)==0)
{
cout << "First 3 characters of two strings are equal" << endl;
}
strcat(name," ");
strcat(name,name1);
cout << name << endl;
return(0);
}
The result of the program is:-
The statement
#include<cstring>
includes a header file <cstring> into the program. The statement
l=strlen(name);
computes the length of the string name. The function strlen(name) returns the length of the string name. The length of the string is 18. The statement
if(strstr(name,"good"))
checks whether substring “good” appears in the string name. The function strstr(name,”good”) returns true as “good” appears in string name. The statement
if(strchr(name1,'M'))
checks whether character ‘M’ appears in string name1. The function strchr(name1,’M’) returns true as character ‘M’ appears in string name1. The statement
if(strcmp(name,name1)>0)
compares two strings name and name1. It returns false as string name< string name1.
The statement
strcpy(stri,name1);
copies content of string name1 into string stri. The statement
strncat(stri,name,4);
concatenates first 4 letters of string name to string stri. The statement
if(strncmp(stri,name1,3)==0)
compares first 3 characters of string name1 with first 3 characters of string stri. It returns true as first 3 characters of name1 and stri are same. The statement
strcat(name," ");
concatenates whitespace at the end of the string name. The statement
strcat(name,name1);
concatenates content of string name1 at the end of string name.
Go to the previous lesson or proceed to the next lesson