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