Write strcmp () function by yourself

Source: Internet
Author: User

I found a library function strcmp () source code on the Internet:

int strcmp (const char * src, const char * dst){        int ret = 0 ;        while( ! (ret = *(unsigned char *)src - *(unsigned char *)dst) && *dst)                ++src, ++dst;          if ( ret < 0 )                ret = -1 ;        else if ( ret > 0 )                ret = 1 ;        return( ret );}

I initially wrote:

int strcmp(char const *s1, char const *s2){int i = 0;while(1) {if(s1[i] == '\0' && s2[i] == '\0')return 0;else if(s1[i] > s2[i])return 1;else if(s1[i] < s2[i])return -1;i++;}} 

Then we can streamline the process as follows:

int strcmp(char const *s1, char const *s2){int ret, i = 0;while(1) {ret = s1[i] - s2[i];if(ret || !s1[i] || !s2[i])return ret;i++;}} 

Continue to streamline:

Int strcmp (char const * S1, char const * S2) {int ret, I = 0; while (1) {ret = S1 [I]-S2 [I]; if (Ret |! S1 [I]) // as long as one of the strings encounters \ 0, RET will not be zero. return ret; I ++ ;}}

However, if the input pointer is null, it will crash, and the improvement is as follows:

Int strcmp (char const * S1, char const * S2) {int ret, I = 0; If (! S1 |! S2) return S1-S2; while (1) {ret = S1 [I]-S2 [I]; If (Ret |! S1 [I]) // as long as one of the strings encounters \ 0, RET will not be zero. return ret; I ++ ;}}

Comments

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.