相关函数:wcscmp
一般形式:strcmp(字符串1,字符串2) 说明: 当s1<s2时,返回值<0 当s1=s2时,返回值=0 当s1>s2时,返回值>0 即:两个字符串自左向右逐个字符相比(按ASCII值大小相比较),直到出现不同的字符或遇'\0'为止。特别注意:strcmp(const char *s1,const char * s2)这里面只能比较字符串,不能比较数字等其他形式的参数。
代码1:
#include <stdio.h> //计算字符串长度 int length (char str) { int len = 0; while (*str++) len++; return len; } //字符串的比较 int Mystrcmp (char *str1, char *str2) { if(length(str1) != length(str2)) //若字符串长度不相等返回 1 { return 1; } while (*str1) { if (*(str1++) != *(str2++)) //字符串中有字符不相等返回 1 { return 1; } } return 0; //遍历后字符串没有不相等的字符 } int main() { char str1[] = "hello"; char str2[] = "hello"; int res = Mystrcmp (str1, str2); printf ("%d\n",res); return 0;}代码2 : #include <stdio.h> int Mystrncmp (char *str1, char *str2, int n) { int len = 0; while (len < n) //前n个字符比较若有不相等的字符返回 1 { if(*str1 != *str2) { return 1; } len ++; str1++; str2++; } return 0; //相等返回 0 } int main () { char str1[] = "hello"; char str2[] = "hello world"; int n; scanf ("%d", &n); int res = Mystrncmp (str1, str2, n); printf ("%d\n",res); return 0; }