w3resource

C Programming: Compare two strings without using string library functions

C String: Exercise-6 with Solution

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

Sample Solution:

C Code:

 // C program to compare the two strings
// without using strcmp() function
#include <stdio.h>
#define str_size 100 //Declare the maximum size of the string
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;
}

Sample Output:

Check the length of two strings:
--------------------------------
Input the 1st string : aabbcc
Input the 2nd string : abcdef

String1: aabbcc
String2: abcdef

Strings are not equal.

Sample Output:

Check the length of two strings:
--------------------------------
Input the 1st string : aabbcc
Input the 2nd string : aabbcc

String1: aabbcc
String2: aabbcc

Strings are equal.

Flowchart:

Flowchart: Compare two strings without using string library functions

C Programming Code Editor:

Improve this sample solution and post your code through Disqus.

Previous: Write a program in C to count the total number of words in a string.
Next: Write a program in C to count total number of alphabets, digits and special characters in a string.

What is the difficulty level of this exercise?



C Programming: Tips of the Day

How to measure time in milliseconds using ANSI C?

There is no ANSI C function that provides better than 1 second time resolution but the POSIX function gettimeofday provides microsecond resolution. The clock function only measures the amount of time that a process has spent executing and is not accurate on many systems.

You can use this function like this:

structtimevaltval_before, tval_after, tval_result;

gettimeofday(&tval_before, NULL);

// Some code you want to time, for example:
sleep(1);

gettimeofday(&tval_after, NULL);

timersub(&tval_after, &tval_before, &tval_result);

printf("Time elapsed: %ld.%06ld\n", (long int)tval_result.tv_sec, (long int)tval_result.tv_usec);

This returns Time elapsed: 1.000870 on my machine.

Ref : https://bit.ly/3lpwoMn