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 <iostream> # include <assert. h> using namespace STD; int main () {char a [] = "aaaae"; char B [] = "aaaaf"; int I = strcmp (A, B ); cout <I <Endl; Int J = strncmp (a, B, 4); // compare only the first n characters of cout <j <Endl; system ("pause"); Return 0 ;}
The running result is-1, 0;
II. Implementation of strcmp () and strncmp ()
# Include <iostream> # include <assert. h> using 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 <I <Endl; Int J = strncmp_m (a, B, 4 ); // compare only the first n characters of cout <j <Endl; System ("pause"); Return 0 ;}
The running result is-. The strcmp () and strncmp () functions are implemented.
Description and implementation of string functions-strcmp () and strncmp ()