compares character strings str1 and str2, and returns negative, zero, or positive if str1 is lexicographically less than, equal to, or greater than str2, respectively - C String

C examples for String:String Function

Description

compares character strings str1 and str2, and returns negative, zero, or positive if str1 is lexicographically less than, equal to, or greater than str2, respectively

int strcomp(char *str1, char *str2)
{
  int j;
  for(j = 0; str1[j] == str2[j]; j++)
    if(str1[j] == '\0')
      return 0;
  return str1[j] - str2[j];
}

Demo Code

/* Count spaces */
#include <stdio.h>

int strcomp(char *str1, char *str2)
{
   int j;//from  ww  w.ja va2  s  .c o m
   for (j = 0; str1[j] == str2[j]; j++)
      if (str1[j] == '\0')
         return 0;
   return str1[j] - str2[j];
}
int main(void)
{
   char *str = "this is a  test";
   char *s = "asdfasdfasdf";

   int r = strcomp(s, str);

   printf("%d",r);

   return 0;
}

Result


Related Tutorials