Test Question 3 string comparison function int strcmp (const char * str1, const char * str2)

Source: Internet
Author: User
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. 
 

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.