Home  >  Article  >  Backend Development  >  What function is used in C language to compare string sizes?

What function is used in C language to compare string sizes?

烟雨青岚
烟雨青岚Original
2020-07-06 11:08:2114434browse

C language uses the "strcmp()" function to compare string sizes. The syntax is "int strcmp(const char *s1, const char *s2);"; the parameters "s1" and "s2" respectively represent the two strings that need to be compared.

What function is used in C language to compare string sizes?

The c language uses the strcmp() function to compare string sizes.

Header file:

#include <string.h>

strcmp() is used to compare strings (case sensitive), its prototype is:

int strcmp(const char *s1, const char *s2);

[Parameter] s1, s2 are the two strings that need to be compared.

The comparison of string sizes is determined by the order on the ASCII code table, and this order is also the value of the characters.

strcmp() first subtracts the first character value of s2 from the first character value of s1. If the difference is 0, then continue to compare the next character. If the difference is not 0, return the difference value. . For example, comparing the strings "Ac" and "ba" will return the difference (-33) between the characters "A" (65) and 'b' (98).

[Return value] If the strings of parameters s1 and s2 are the same, 0 will be returned. If s1 is greater than s2, a value greater than 0 is returned. If s1 is less than s2, a value less than 0 is returned.

Note: strcmp() compares in binary and does not consider multi-byte or wide-byte characters; if you consider localization requirements, please use the strcoll() function.

Example:

#include <string.h>
main(){
    char *a = "aBcDeF";
    char *b = "AbCdEf";
    char *c = "aacdef";
    char *d = "aBcDeF";
    printf("strcmp(a, b) : %d\n", strcmp(a, b));
    printf("strcmp(a, c) : %d\n", strcmp(a, c));
    printf("strcmp(a, d) : %d\n", strcmp(a, d));
}

Output result:
strcmp(a, b) : 32
strcmp(a, c) :-31
strcmp(a, d): 0

Recommended tutorial: "C Language"

The above is the detailed content of What function is used in C language to compare string sizes?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn