Sunday 22 July 2012

Comparing two strings using pointers

How to write Program for comparing two strings using pointers*/
//function for comparing two strings
int pstrcmp(const char *str1,const char *str2)
{
while(*str1!='\0'&&*str2!='\0'&&*str1==*str2)
{
str1++;
str2++;
}
//value returned when strings are of equal length
if(*str1==*str2)
return 0;
else
//value returned when strings are not of equal length
return(*str1-*str2);
}

//main function
main()
{
char str1[100],str2[100];
int n;
clrscr();

//accept two strings from user
printf("Enter some string:");
gets(str1);
printf("Enter second string:");
gets(str2);

//store the value returned by pstrcmp function in n
n=pstrcmp(str1,str2);
//decide which string is greater depending upon its value of n
if(n>0)
printf("First string is greater");
else if(n<0)
printf("Second string is greater");
else
printf("Both the strings are equal");
getch();
}

Share This
Previous Post
Next Post

FYJC XI standard online admisson Process and declaraton of Merit list . Cut off List For prevous year also . 10 Th Results onlne declaraton Maharashtra Region .

0 comments: