Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the comparison algorithm used in "strcmp" - C programming?

Tags:

c

Can any one explain what algorithm used in strcmp to compare two string in C programming ?

I didnt understand the return value from this, It uses any algorithm like 'Levenstien algorithm' to find out distance between two string...

like image 428
Sahal Avatar asked Jun 09 '26 06:06

Sahal


2 Answers

The GNU implementation of the standard C library, glibc, is open source and you can just read strcmp.c if you are curious. There is not much to it. Here it is:

/* Compare S1 and S2, returning less than, equal to or
   greater than zero if S1 is lexicographically less than,
   equal to or greater than S2.  */
int strcmp (const char *p1, const char *p2)
{
  register const unsigned char *s1 = (const unsigned char *) p1;
  register const unsigned char *s2 = (const unsigned char *) p2;
  unsigned reg_char c1, c2;

  do
    {
      c1 = (unsigned char) *s1++;
      c2 = (unsigned char) *s2++;
      if (c1 == '\0')
        return c1 - c2;
    }
  while (c1 == c2);

  return c1 - c2;
}
like image 92
David Grayson Avatar answered Jun 11 '26 22:06

David Grayson


strcmp is not a string distance algorithm. It is a string comparison algorithm and the only thing it is required to tell you is whether the two strings are equal (return code zero) or if not, which of the two strings is "greater" for some meaning of that word (a positive or negative value).

The magnitude of the return result is not specified, i.e. it can always return either 1, 0, or -1; or it can return an actual integral distance for some measure of distance (e.g. Levenstein, simple subtraction, etc.). In practice, strcmp is never implemented with an actual string distance algorithm for performance reasons (do the least amount of work to determine the equivalence of two strings and get out).

like image 20
Mahmoud Al-Qudsi Avatar answered Jun 11 '26 22:06

Mahmoud Al-Qudsi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!