The realization of strcmp
Introduction to the function prototype: extern int strcmp (const char *s1,const char * s2);
Usage:Add header file #include <string.h>
function:Compares strings S1 and S2.
general form:strcmp (String 1, String 2)
return Value:
when S1<s2, the return value <0
When S1=s2, the return value =0
When S1>s2, the return value >0
That is: two strings are compared from left to right by character (compared to the size of the ASCII value) until there are different characters or "". such as: "A" < "B" "a" > "a" "Computer" > "Compare"
Special attention:
1. strcmp (const char *s1,const char * s2) This can only be compared to strings, not to compare numbers and other forms of parameters.
2. With respect to the return value, the standard only stipulates three values: less than 0, 0, greater than 0. What is the value of the compiler to set their own, so the programming time to judge is less than or equal to more than, can not determine whether equal to 1 or-1, such as in VC strcmp ("123", "1234") return-1, and in the TC return-52.
Below is my own realization, deficiencies, also hope to correct! (I am here to return -1,0,1)
Copy Code code as follows:
#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)
{
++STR1;
++STR2;
}
if (*str1 > *str2)
return 1;
if (*str1 < *STR2)
return-1;
Else
return 0;
}</p>int _tmain (int argc, _tchar* argv[])
{
Char *str1 = "Hello World";
Char *str2 = "Hello World";
cout << mystrcmp (STR1,STR2) << Endl;
return 0;
}