C Programming Coding Strings

C program to compare two strings

C program to compare two strings - C Programming - This c program to compares two strings using strcmp, without strcmp and using pointers.

This c program to compare two strings using strcmp, without strcmp and using pointers. For comparing strings without using library function see another code below

C program to compare two strings using strcmp

#include <stdio.h>
#include <string.h>
 
int main()
{
   char a[100], b[100];
 
   printf("Enter the first string\n");
   gets(a);
 
   printf("Enter the second string\n");
   gets(b);
 
   if (strcmp(a,b) == 0)
      printf("Entered strings are equal.\n");
   else
      printf("Entered strings are not equal.\n");
 
   return 0;
}

Function strcmp is case sensitive and returns 0 if both strings are equal.

C program to compare two strings without using strcmp

Here we create our own function to compare strings.

#include <stdio.h>
 
int compare_strings(char [], char []); 
 
int main()
{
   int flag;
   char a[1000], b[1000];
 
   printf("Input first string\n");
   gets(a);
 
   printf("Input second string\n");
   gets(b);
 
   flag = compare_strings(a, b);
 
   if (flag == 0)
      printf("Entered strings are equal.\n");
   else
      printf("Entered strings are not equal.\n");
 
   return 0;
}
 
int compare_strings(char a[], char b[])
{
   int c = 0;
 
   while (a[c] == b[c]) {
      if (a[c] == '\0' || b[c] == '\0')
         break;
      c++;
   }
 
   if (a[c] == '\0' && b[c] == '\0')
      return 0;
   else
      return -1;
}

C program to compare two strings using pointers

In this method we will make our own function to perform string comparison, we will use character pointers in our function to manipulate string .

#include<stdio.h>
 
int compare_string(char*, char*);
 
int main()
{
    char first[1000], second[1000], result;
 
    printf("Input first string\n");
    gets(first);
 
    printf("Input second string\n");
    gets(second);
 
    result = compare_string(first, second);
 
    if (result == 0)
       printf("Both strings are same.\n");
    else
       printf("Entered strings are not equal.\n");
 
    return 0;
}
 
int compare_string(char *first, char *second) {
   while (*first == *second) {
      if (*first == '\0' || *second == '\0')
         break;
 
      first++;
      second++;
   }
 
   if (*first == '\0' && *second == '\0')
      return 0;
   else
      return -1;
}
READ  C Programming - Given two strings, find if first string is a subsequence of second

About the author

Venkatesan Prabu

Venkatesan Prabu

Wikitechy Founder, Author, International Speaker, and Job Consultant. My role as the CEO of Wikitechy, I help businesses build their next generation digital platforms and help with their product innovation and growth strategy. I'm a frequent speaker at tech conferences and events.

Add Comment

Click here to post a comment

X