In-depth discussion on strcmp string comparison using C ++

Source: Internet
Author: User

Implementation of strcmp
Function introduction prototype: extern int strcmp (const char * s1, const char * s2 );
Usage:Add the header file # include <string. h>
Function:Compares s1 and s2 strings.
General format:Strcmp (string 1, string 2)
Return Value:
When s1 <s2, return value <0
When s1 = s2, the return value is 0.
When s1> s2, return value> 0
That is, two strings are compared from left to right one by one (compare by ASCII value) until different characters or '\ 0' appear. For example: "A" <"B" a ">" A "" computer ">" compare"
Note:
1. strcmp (const char * s1, const char * s2) can only compare strings, numbers, and other parameters.
2. For the return value, the standard only specifies three values: Less Than Zero, zero, and greater than zero. The compiler determines the specific value. Therefore, when programming, it cannot determine whether the value is greater than or equal to 1 or-1, for example, strcmp ("123", "1234") in VC ") -1 is returned, and-52 is returned in TC.

The following is my own implementation. I hope to correct it! (Here I return-1, 0, 1)Copy codeThe Code is 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.