First understand the difference between string and character array
First, the character array is different from the string. The character array may not contain '\ 0', And the last character of the string must be' \ 0 '. Second, compare the two strings to compare the ASCII code starting from the first character of the two strings. If the first character is the same, check the second character, and so on. For example, "AB" is greater than "cdefghijk. Third, as long as '\ 0' appears in the string, it does not exist at all. The character array is, for example, char s [5] = {'A',' B ', '\ 0', 'E', 'K'}, and the string is Char s [5] = "ABCD ". fourth, if a string is a substring starting from the beginning of another string, the parent string is large. If you know the first three points, this is of course, because the last digit of the parent string is not '\ 0', And the substring is' \ 0.
// The string function determines which string is large based on the return value. If the return value is equal to zero, the return value is equal. If the return value is smaller than zero, the return value is 2. If the return value is greater than zero, the return value is 1.
Int strcmp (const char * str1, const char * str2)
{
assert (str1! = NULL & str2! = NULL ); while (* str1 & * str2 & (* str1 = * str2 ))
{
str1 ++; // do not write it as * STR ++. Here is the address plus
str2 ++;
}
return * str1-* str2;
}
1. first, the values of the two input strings cannot be changed. Therefore, you must add the const modifier
2. exclude null strings using assertions
3. while determines that the while loop is executed only when string 1 or string 2 are equal or both are equal, because if one of the strings has been compared to the end, and the other has not been compared, obviously, you do not need to continue the comparison
4. returns the difference between two letters.