1、函数原型
#include <stdio.h> int strncmp(const char *s1, const char *s2, size_t n) { while(n && *s1 && *s2) { if(*s1 != *s2) return (unsigned char)*s1 - (unsigned char)*s2; n--; s1++; s2++; } if(!n) return 0; if(*s1) return 1; return -1; } int main(void) { char str1[128] = "abcd"; char str2[128]; printf("str2: "); scanf("%s", str2); unsigned n; printf("n = "); scanf("%u", &n); int tmp = strncmp(str1, str2, n); if(tmp > 0) puts("str1 > str2"); else if(tmp == 0) puts("str1 = str2"); else puts("str1 < str2"); return 0; }
改进
↓
#include <stdio.h> int strncmp(const char *s1, const char *s2, size_t n) { while(n && *s1 && *s2) { if(*s1 != *s2) return (unsigned char)*s1 - (unsigned char)*s2; n--; s1++; s2++; } if(!n) return 0; if(*s1 == *s2) return 0; if(*s1) return 1; return -1; } int main(void) { char str1[128] = "abcd"; char str2[128]; printf("str2: "); scanf("%s", str2); unsigned n; printf("n = "); scanf("%u", &n); int tmp = strncmp(str1, str2, n); if(tmp > 0) puts("str1 > str2"); else if(tmp == 0) puts("str1 = str2"); else puts("str1 < str2"); return 0; }
2、头文件
#include <stdio.h> #include <string.h> int main(void) { char str1[128] = "abcd"; char str2[128]; printf("str2: "); scanf("%s", str2); unsigned n; printf("n = "); scanf("%u", &n); int tmp = strncmp(str1, str2, n); if(tmp > 0) puts("str1 > str2"); else if(tmp == 0) puts("str1 = str2"); else puts("str1 < str2"); return 0; }