Q29 Write a program in C to compare two strings without using string library functions.

Admin

Write a program in C to compare two strings without using string library functions.

#include <stdio.h>
#define str_size 100
int test(char* s1, char* s2)
{
         int flag = 0;
         while (*s1 != '\0' || *s2 != '\0') {
                  if (*s1 == *s2) {
                            s1++;
                            s2++;
                  }
        else if ((*s1 == '\0' && *s2 != '\0')||(*s1 != '\0' && *s2 == '\0')||*s1 != *s2) {flag=1;
                            break;
                  }
         }
  return flag;
}
int main(void)
{
char str1[str_size], str2[str_size];
   int flg=0;
   printf("\nInput the 1st string : ");
   fgets(str1, sizeof str1, stdin);
   printf("Input the 2nd string : ");
   fgets(str2, sizeof str2, stdin);          
   printf("\nString1: %s", str1);
   printf("String2: %s", str2);
   flg = test(str1, str2);
    if(flg == 0)
   {
       printf("\nStrings are equal.\n");
   }
   else if(flg == 1)
   {
      printf("\nStrings are not equal.");
   }
    return 0;
}

Output

Input the 1st string : Hello
Input the 2nd string : World

String1: Hello
String2: World

Strings are not equal.

Input the 1st string : Hello
Input the 2nd string : Hello

String1: Hello
String2: Hello

Strings are equal.

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.