ProAnswers.org

C program to compare two strings without using strcmp() function

2 Likes

strcmp() function compares two strings lexicographically. strcmp is declared in stdio.h
Case 1: when the strings are equal, it returns zero.
Case 2: when the strings are unequal, it returns the difference between ascii values of the characters that differ.
a) When string1 is greater than string2, it returns positive value.
b) When string1 is lesser than string2, it returns negative value.

Syntax:
int strcmp (const char *s1, const char *s2);

////*********Program: to compare two strings. *********////////////////

#include<stdio.h>
#include<string.h>
int cmpstr(char s1[10], char s2[10]);

int main()
{
 char arr1[10] = "Nodalo";
 char arr2[10] = "nodalo";
 printf(" %d", cmpstr(arr1, arr2));
/////////////////cmpstr() is equivalent of strcmp()
 return 0;
}

//////////////////s1, s2 are strings to be compared
int cmpstr(char s1[10], char s2[10]) {
/////////////// //strlen function returns the length of argument string passed
 int i = strlen(s1);
 int k = strlen(s2);
 int bigger;
 
 if (i < k)
{
  bigger = k;
 }

 else if (i > k)
{
  bigger = i;
 }
 else
{
  bigger = i;
 }

 //loops 'bigger' times
 for (i = 0; i < bigger; i++)
{
  //if ascii values of characters s1[i], s2[i] are equal do nothing
  if (s1[i] == s2[i]) {
  }
  //else return the ascii difference
  else {
   return (s1[i] - s2[i]);
  }
 }

 //return 0 when both strings are same
 //This statement is executed only when both strings are equal
 return (0);
}

Output:
-32

Reason:
cmpstr() is a function that illustrates C standard function strcmp(). Strings to be compared are sent as arguments to cmpstr().
Each character in string1 is compared to its corresponding character in string2. Once the loop encounters a differing character in the strings, it would return the ascii difference of the differing characters and exit.

#include<iostream.h>
#include<stdio.h>
#include<conio.h>
void main()

{
	clrscr();
	int c=0;
	char a[10];

	char b[10];
	gets(a);
	gets(b);
	for(int i=0,j=0;b[i]!='\0'||a[j]!='\0';i++,j++)
	{
		if(a[i]!=b[j])
		{
			c++;
		     
		}

	}
	if(c==0)
		cout<<"string match";
	else
		cout<<"string does not match";

getch();
}
#include <stdio.h>
#include <string.h>

 void stringcmp(char s1[], char s2[]);

int main()
{
   
   char str1[10],str2[10];

   printf("\nEnter first String:");
   scanf("%s",str1);

   printf("\nEnter second String:");
   scanf("%s",str2);

   stringcmp(str1,str2);
   
   return 0;
}

void stringcmp(char *s1, char *s2)
{
   int i,j;

   for(i=0;s1[i]!='\0';i++)
   {
      for(j=0;s2[j]!='\0';j++)
      {
            if(s1[i] == s2[j])
            continue;
      }
   }

   if (i==j)
   {
     printf("String s1:%s and s2:%s are EQUAL\n",s1,s2);
   }
   else
     printf("String s1:%s and s2:%s are NOT EQUAL\n",s1,s2);
}