
c语言比较函数
strcmp()函数:
#define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<string.h> void test() { //字符串的比较 char s1[32] = { 0 }; fgets(s1, sizeof(s1), stdin); //fgets会从缓冲区中带走\\n回车符 //需要把字符串结尾的\\n改为\\0 s1[strlen(s1) - 1] = '\\0'; char s2[32] = "dhy"; if (strcmp(s1, s2) == 0) { printf("相等"); } if (strcmp(s1, s2) == 1) { printf("s1>s2"); } if (strcmp(s1, s2) == -1) { printf("s1<s2"); } } int main() { test(); return 0; }注意:strlen(s1)是数组中存储最后一个非空白字符后面一个元素
strncmp函数:
#define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<string.h> void test() { //字符串的比较 char s1[32] = { 0 }; fgets(s1, sizeof(s1), stdin); //fgets会从缓冲区中带走\\n回车符 //需要把字符串结尾的\\n改为\\0 //如果改成sizeof,要减去2,因为多包含一个\\0 s1[strlen(s1) - 1] = '\\0'; char s2[32] = "dhy"; if (strncmp(s1, s2,3) == 0) { printf("相等"); } if (strncmp(s1, s2,3) == 1) { printf("s1>s2"); } if (strncmp(s1, s2,3) == -1) { printf("s1<s2"); } } int main() { test(); return 0; }👁️ 阅读量:0
© 版权声明:本文《c语言比较函数》内容均为本站精心整理或网友自愿分享,如需转载请注明原文出处:https://www.zastudy.cn/wen/1686491167a268424.html。