C Program to compare two strings

C Strings:
C Program to accepts two strings and compare them, Finally it prints whether both are equal, or first string is greater than the second or the first string is less than the second string. The string comparison starts with the first character in each string and continues with subsequent characters until the corresponding characters differ or until the end of the strings is reached. Read more about C Programming Language .

/***********************************************************
* You can use all the programs on  www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact [email protected]
* To find more C programs, do visit www.c-program-example.com
* and browse!
* 
*                                  Happy Coding
***********************************************************/              
#include<stdio.h>
#include<conio.h>

void main()
{
 int count1=0,count2=0,flag=0,i;
 char str1[10],str2[10];

 clrscr();
 puts("Enter a string:");
 gets(str1);

 puts("Enter another string:");
 gets(str2);
 /*Count the number of characters in str1*/
 while (str1[count1]!='')
  count1++;
 /*Count the number of characters in str2*/
 while (str2[count2]!='')
  count2++;
 i=0;

 /*The string comparison starts with the first character in each string and
 continues with subsequent characters until the corresponding characters
 differ or until the end of the strings is reached.*/

 while ( (i < count1) && (i < count2))
 {
  if (str1[i] == str2[i])
  {
   i++;
   continue;
  }
  if (str1[i]<str2[i])
  {
   flag = -1;
   break;
  }
  if (str1[i] > str2[i])
  {
   flag = 1;
   break;
  }
 }

 if (flag==0)
  printf("Both strings are equaln");
 if (flag==1)
  printf("String1 is greater than string2n", str1, str2);
 if (flag == -1)
  printf("String1 is less than string2n", str1, str2);
 getch();
}
Read more Similar C Programs
Searching in C

C Strings

You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can Follow @c_program

You can discuss these programs on our Facebook Page. Start a discussion right now!

Share this program with your Facebook friends now! by liking it
Like to get updates right inside your feed reader? Grab our feed!
(c) www.c-program-example.com

Leave a Reply