strcmp Function

Compares two strings.

Include

<string.h>

Prototype

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

Arguments

s1
first string
s2
second string

Return Value

Returns a positive number if s1 is greater than s2, zero if s1 is equal to s2 or a negative number if s1 is less than s2.

Remarks

This function compares successive characters from s1 and s2 until they are not equal or the null terminator is reached.

Example

#include <string.h>
#include <stdio.h>

int main(void)
{
  char buf1[50] = "Where is the time?";
  char buf2[50] = "Where did they go?";
  char buf3[50] = "Why?";
  int res;

  printf("buf1 : %s\n", buf1);
  printf("buf2 : %s\n", buf2);
  printf("buf3 : %s\n\n", buf3);

  res = strcmp(buf1, buf2);
  if (res < 0)
    printf("buf1 comes before buf2\n");
  else if (res == 0)
    printf("buf1 and buf2 are equal\n");
  else
    printf("buf2 comes before buf1\n");
  printf("\n");

  res = strcmp(buf1, buf3);
  if (res < 0)
    printf("buf1 comes before buf3\n");
  else if (res == 0)
    printf("buf1 and buf3 are equal\n");
  else
    printf("buf3 comes before buf1\n");
  printf("\n");

  res = strcmp("Why?", buf3);
  if (res < 0)
    printf("\"Why?\" comes before buf3\n");
  else if (res == 0)
    printf("\"Why?\" and buf3 are equal\n");
  else
    printf("buf3 comes before \"Why?\"\n");
}

Example Output

buf1 : Where is the time?
buf2 : Where did they go?
buf3 : Why?

buf2 comes before buf1

buf1 comes before buf3

"Why?" and buf3 are equal