The difference between strcmp and strncmp

================== 

https://blog.csdn.net/jianghong678/article/details/47152907

Both strcmp and strncmp are used to compare strings, the difference lies in whether they can compare strings of specified length.

strcmp

The C/C++ function compares two strings and 
sets the two strings as str1 and str2. 
If str1==str2, it returns zero; 
if str1 > str2, it returns a positive number; 
if str1<str2, it returns a negative number.

That is, the two strings are compared character by character from left to right (compared according to the ASCII value) until different characters appear or '\0' is encountered.

For example: 
the return value of strcmp("abcd","abcd") is 0; the return value of 
strcmp("abcd","dcba") is -1; the return value of 
strcmp("dcba","abcd") is 1 ;

There is another situation: 
the return value of strcmp("A","C") is -2; the return value of 
strcmp("C","A") is 2; 
the exact value depends on the implementation of different c, I don't have -2 and 2 appearing in VS2013, still -1 and 1 appear.

Special attention : strcmp(const char  s1, const char  s2) can only compare strings, which can be used to compare two string constants, or compare arrays and string constants, but cannot compare other parameters such as numbers.

strncmp

The strncmp function is specified to compare size characters. That is, if the first size characters of the strings s1 and s2 are the same, the function returns a value of 0. The function of this function is to compare the first maxlen characters of the strings str1 and str2. If the first maxlen bytes are completely equal, the return value = 0; during the comparison of the first maxlen bytes, if str1[n] and str2[n] are not equal, compare the first n bits of str1 and str2 in turn, and set i (i< n) is the first different bit of the two strings, then return (str1[i]-str2[i]).

For example; 
str1=”ABCDHG”, str2=”ABCDEF” 
The return value of strncmp(str1,str2,4) is 0; The return value of 
strncmp(str1,str2,5) is 1;

Description: Compare the size of the strings str1 and str2, if str1 is less than str2, the return value is <0, otherwise if str1 is greater than str2, the return value is >0, if str1 is equal to str2, the return value is =0, len refers to str1 The number of characters to compare with str2. The function of this function is to compare the first len ​​characters [1] of the strings str1 and str2. 
Tip: This function is case sensitive.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325726546&siteId=291194637