String Functions In CPP

1. strlen() – This function returns the length of the string as seen in the output. This function does not return the null character(if there is space between strings it will not count).

#include<iostream.h>
#include<conio.h>
#include<string.h>

void main()
{
clrscr();
int i;
char str[20];
cout << "enter the string" << endl;
cin >> str;

i=strlen(str);
cout << i << endl;
getch();
}

Output:
enter the string
tanmay
6

2. strupr() – This function converts the given string into uppercase.

#include<iostream.h>
#include<conio.h>
#include<string.h>


void main()
{
clrscr();

char name[10];
cout << "enter any name" << endl;       
cin >> name;
strupr(name);
cout << name << endl;
getch();
}

Output:
enter any name
tanmay
TANMAY

3. strlwr() – This function will convert the given string into lower case.

#include<iostream.h>
#include<conio.h>
#include<string.h>


void main()
{
clrscr();

char name[10];
cout << "enter any name" << endl;      
cin >> name;
strlwr(name);
cout << name << endl;
getch();
}

Output:
enter any name
TANMAY
tanmay

4. strrev() – This function will convert the given string into reverse order.

#include<iostream.h>
#include<conio.h>
#include<string.h>


void main():
{
clrscr();
char name[10];
cout << "enter any name" << endl;       
cin >> name;
strrev(name);
cout << name << endl;
getch();
}

Output:
enter any name
tanmay
yamnat

5. strcpy() – This function is used copy one string into another.

#include<iostream.h>
#include<conio.h>
#include<string.h>


void main()
{
clrscr();
char name1[10];
char name2[10];

cout <<"enter any name"<<endl;       
cin >> name1;

cout << "enter any name"<<endl;
cin >> name2;

strcpy(name1,name2);        
cout << name1 << endl;       
cout << name2 << endl;

getch();
}
Output:
enter any name
tanmay
enter any name
shivam

shivam
shivam

6. strcmp() – This function takes two string and it will compare it.

#include<iostream.h>
#include<conio.h>
#include<string.h>


void main()
{
clrscr();
char name1[10];
char name2[10];

cout << "enter any name"<<endl;       // to input a name/string
cin >> name1;

cout << "enter any name"<<endl;
cin >> name2;

int a=strcmp(name1,name2);


cout << a << endl;                   // if a is 0 then string are same if a is other than 0 then string are different

if (a==0)
{
 cout << "same";
}
else
{
 cout << "different";
}

getch();
}
Output:
enter any name
tanmay
enter any name
tanmay
0
same

7. strcat()-  This function will concat the two given strings.

#include<iostream.h>
#include<conio.h>
#include<string.h>


oid main()
{
clrscr();
char name1[10],name2[10];


cout <<"enter any name";       
cin >> name1;

cout <<"enter any name";
cin >> name2;

strcat(name1,name2);      //name 1 and name2 will be added   // concatenated result will be stored into first variable that is name1;
cout << name1;
getch();
}

Output:
enter any name
tanmay
enter any name
jain
tanmayjain

 

Leave a Reply