原型: extern int strcmp(const char *s1, const char *s2)
所在的头文件:string.h
功能比较字符串s1与s2
#include <iostream> #include <string> using namespace std; int main() { string stro="jdfakdjfalkdjlkadasdasdasdasdasdasdasd"; string strt="fjaksldjflkadjflakjdlkfjaldkjf"; bool myStrcmp(const string &s1, const string &s2); int i=myStrcmp(stro,strt); cout<<i<<endl; return 0; } bool myStrcmp(const string &s1, const string &s2) { return s1.size() < s2.size(); }
int strcmp(const char *s1, const char *s2) { int ret=0; assert((NULL!=str1)&&(NULL!=str2)); while(!(ret=*(unsigned char*)s1-*(unsigned char*)s2&&(*s1)) { s1++; s2++; } if (ret>0) return 1; else if (ret<0) return -1; return 0; }
int strcmp(char *s1,char *s2) { int i=0; while(*(s1+i)==*(s2+i)) if(*(s1+i++)=='0') return 0; return (*(s1+i)-(*(s2+i)));//结果返回第一个不相同的字符ASCII的差值 }源码3:
intstrcmp(constchar*str1,constchar*str2) { while(*str1==*str2) { if(*str1=='\0') return0; str1++; str2++; } return*str1-*str2; }
int strcmp(const char* str1, const char* str2) { while ((*str1) && (*str1 == *str2)) { str1++; str2++; } if (*(unsigned char*)str1 > *(unsigned char*)str2) { return 1; } else if (*(unsigned char*)str1 < *(unsigned char*)str2) { return -1; } else { return 0; } }
int strcmp(const char *str1, const char *str2) { for ( ; *str1 == *str2; str1++, str2++) { if (*str1 == '\0') return 0; } if (*(unsigned char*)str1 > *(unsigned char*)str2) { return 1; } else if (*(unsigned char*)str1 < *(unsigned char*)str2) { return -1; } //如果只返回正负的话可以用 return *(unsigned char*)str1 - *(unsigned char*)str2; }