C++ implementation of STRCMP string comparison in depth

  • 2020-04-02 01:02:37
  • OfStack

The realization of the STRCMP
Function profile prototype: extern int STRCMP (const char *s1,const char * s2);
Usage: Header file #include < String. H >
Function: Compare the strings s1 and s2.
General form: STRCMP (string 1, string 2)
The return value:
When s1 < S2, returns a value < 0
When s1=s2, the return value =0
When s1 > S2, returns a value > 0
That is, two strings are compared character by character from left to right (ASCII) until different characters appear or '\0' occurs. Such as: "A" < "B" "a" > "A" "computer" > "Compare"
Special note:
1.   STRCMP (const char *s1,const char * s2) this can only compare strings, not other forms of arguments such as Numbers.
2.   With respect to the return value, the standard simply specifies three values: less than zero, zero, and greater than zero. The specific value is determined by the compiler itself, so when programming, it determines whether the value is less than or greater than, and cannot determine whether it is equal to 1 or -1. For example, in VC, STRCMP ("123","1234") returns -1, and in TC returns -52.

The following is my own realization, shortcomings, also hope to point out! (my return here is minus 1,0,1)

#include "stdafx.h"
#include <iostream>
#include <assert.h>
using namespace std;
<P>int mystrcmp(const char* str1,const char* str2)
 assert(str1 != NULL && str2 != NULL);</P><P> while(*str1 && *str2 && *str1 == *str2)
 if (*str1 > *str2)
  return 1;
 if (*str1 < *str2)
  return -1;
  return 0;
}</P>int _tmain(int argc, _TCHAR* argv[])
 char *str1 = "Hello World";
 char *str2 = "Hello world";
 cout << mystrcmp(str1,str2) << endl;
 return 0;

Related articles: