A deep discussion on the implementation of strcmp string comparison in C + + _c language

Source: Internet
Author: User
Tags assert function prototype strcmp
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;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.