Compare the size of a string

Source: Internet
Author: User

// Function: Compare the string size
// If str1> str2 returns 1
// If str1 = str2, 0 is returned.
// If str1 <str2 returns-1
Char zstrncmp (unsigned char * str1, unsigned char * str2, byte num)
{
While (num! = 0)
{
If (* str1) = (* str2 ))
{
Str1 ++;
Str2 ++;
Num --;
}
Else if (* str1)> (* str2 ))
Return (1 );
Else
Return (-1 );
}
Return (0 );
}
 
 
If you simply compare the length, you can directly call a function similar to strlen () to compare it.
If the string size is compared, the ASCII code size of the character is compared. You can search the ASCII code table to find the size of each ASCII character.
During comparison, set a counter, starting from scratch, repeating until the character ending with the shortest, and comparing one digit by one,
1. If the nth ASCII value of string 1 is equal to the nth ASCII value of string 2, continue to compare the next
2. If the nth ASCII value of string 1 is greater than the nth ASCII value of string 2, the output result is: 1, indicating string 1> string 2; www.2cto.com
3. If the nth ASCII value of string 1 is less than the nth ASCII value of string 2, the output result is:-1 indicates string 1 <string 2;
4. If the ASCII code value of each digit is equal and the length is the same, the output result is: 0 indicating string 1 = string 2;
5. if String 1 is the first m bit of string 2, for example, abcd is compared with abcdef, string 1 <string 2. the reason is that, to 5th bits, the ASCII value of string 1 is 0, and the ASCII value of string 2 is 'E', that is, the decimal 101,
Of course the string is 2.
Specifically, cds and lesoqd start from the first place. 'C' and 'l' are compared, of course, 'C' <'L'. Therefore, "cds" <"lesoqd"
The commonly used ascii sequence is from small to large: 0 .. 9, A. Z, a. z.

Related Article

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.