您好,欢迎访问一九零五行业门户网

在C/C++中,strcmp()函数用于比较两个字符串

the function strcmp() is a built-in library function and it is declared in “string.h” header file. this function is used to compare the string arguments. it compares strings lexicographically which means it compares both the strings character by character. it starts comparing the very first character of strings until the characters of both strings are equal or null character is found.
if the first character of both strings are equal, it checks second character and so on. this process will be continued until null character is found or both characters are unequal.
here is the syntax of strcmp() in c language,
int strcmp(const char *leftstr, const char *rightstr );
this function returns the following three different values based on the comparison.
1.zero(0) − it returns zero if both strings are identical. all characters are same in both strings.
here is an example of strcmp() when both strings are equal in c language,
example live demo
#include<stdio.h>#include<string.h>int main() { char str1[] = "tom!"; char str2[] = "tom!"; int result = strcmp(str1, str2); if (result==0) printf("strings are equal"); else printf("strings are unequal"); printf("\nvalue returned by strcmp() is: %d" , result); return 0;}
outputstrings are equalvalue returned by strcmp() is: 0
2.大于零(>0) − 当左字符串的匹配字符的ascii值大于右字符串的字符时,它返回一个大于零的值。
这里是c语言中strcmp()返回大于零值的一个例子,
示例 在线演示
#include<stdio.h>#include<string.h>int main() { char str1[] = "hello world!"; char str2[] = "hello world!"; int result = strcmp(str1, str2); if (result==0) printf("strings are equal"); else printf("strings are unequal"); printf("\nvalue returned by strcmp() is: %d" , result); return 0;}
outputstrings are unequalvalue returned by strcmp() is: 32
3.小于零(<0) − 当左字符串的匹配字符的ascii值小于右字符串的字符时,它返回一个小于零的值。
下面是c语言中strcmp()的一个例子
例子 在线演示
#include<stdio.h>#include<string.h>int main() { char leftstr[] = "hello world!"; char rightstr[] = "hello world!"; int result = strcmp(leftstr, rightstr); if (result==0) printf("strings are equal"); else printf("strings are unequal"); printf("\nvalue returned by strcmp() is: %d" , result); return 0;}
outputstrings are unequalvalue returned by strcmp() is: -32
以上就是在c/c++中,strcmp()函数用于比较两个字符串的详细内容。
其它类似信息

推荐信息