Description and implementation of string functions-strcmp () and strncmp ()
I. strcmp () and strncmp ()
Strcmp (): strcmp (s1, s2); compares two strings.
Strncmp (): strncmp (s1, s2); compares the first n digits of two strings
Comparison rules: Compare characters (ASCII value) from left to right until different characters or '\ 0' are displayed.
If all the characters are the same, the two strings are considered equal, and the return value is 0;
If different characters appear, compare the first occurrence of different characters. The comparison method is to subtract the first different characters of s2 from the first different characters of s1, return value with the difference value (if the value is greater than 0, 1 is returned. If the value is smaller than 0,-1 is returned ).
Code example:
# Include
# Define deusing namespace std; int main () {char a [] = "aaaae"; char B [] = "aaaaf"; int I = strcmp (a, B); cout <
The running result is-1, 0;
II. Implementation of strcmp () and strncmp ()
# Include
# Define deusing namespace std; int strcmp_m (const char * s1, const char * s2) {assert (s1! = NULL) & (s2! = NULL); while (* s1! = '\ 0' & * s2! = '\ 0') // the first part of the string is the same {if (* s1-* s2> 0) return 1; if (* s1-* s2 <0) return-1; s1 ++; s2 ++;} if (* s1 = '\ 0' & * s2! = '\ 0') // if the value is' \ 0', then return-1 is smaller. if (* s2 = '\ 0' & * s1! = '\ 0') return 1; return 0; // both' \ 0'} int strncmp_m (const char * s1, const char * s2, int n) {assert (s1! = NULL) & (s2! = NULL); while (* s1! = '\ 0' & * s2! = '\ 0' & n) // the front part of the string is the same {if (* s1-* s2> 0) return 1; if (* s1-* s2 <0) return-1; s1 ++; s2 ++; n --;} if (* s1 = '\ 0' & * s2! = '\ 0') // if the value is' \ 0', then return-1 is smaller. if (* s2 = '\ 0' & * s1! = '\ 0') return 1; return 0; // both' \ 0'} int main () {char a [] = "aaaae "; char B [] = "aaaaf"; int I = strcmp_m (a, B); cout <
The running result is-. The strcmp () and strncmp () functions are implemented.