c library function strcmp()

http://www.cplusplus.com/reference/cstring/strcmp/

http://www.tutorialspoint.com/c_standard_library/c_function_strcmp.htm

for the pseudocode: http://stackoverflow.com/questions/12136329/how-does-strcmp-work

http://en.cppreference.com/w/c/string/byte/strncmp

example:

#include<string.h>
#include<stdio.h>
demo(const char* lhs,const char* rhs)
{
    int rc=strcmp(lhs,rhs);
    if(rc==0)
        printf("[%s] equals [%s]\n",lhs,rhs);
    else if(rc<0)
    printf("[%s] precedes [%s]\n",lhs,rhs);
    else if(rc>0)
        printf("[%s] follows [%s]\n",lhs,rhs);

}

int main(void)
{
const char* string="Hello World!";
demo(string, "Hello!");
demo(string, "Hello");
demo(string,"Hello there");
demo("Hello, everybody!" + 12, "Hello, somebody!" + 11);
}

here we are actually comparing the contents of lhs and contents of rhs that is passing from the main function.

declaration can be done by this in nay function

int strcmp(const char* str1,const char* str2)

algorithm should be like this:

define strcmp(str1,str2)

p1=address of first character of str1
p2=address of first character of str2

while contents of p1 is not equal to null.
   if contents of p22 equal to null
       return 1
  
   if contents of p2 greater than contents of p1
       return -1

   if contents of p1 greater than contents of p2
          return 1

    if contents of p2 not equal to null
          return -1

Two things to remember we are defining here the address value not the length of the string and so it is the comparison between contents of the strings not the length . 🙂

It would be a great help, if you support by sharing :)
Author: zakilive

Leave a Reply

Your email address will not be published. Required fields are marked *