C++ 实现strcmp

来源:互联网 发布:东方国信java工资 编辑:程序博客网 时间:2024/05/20 21:21

实现strcmp函数,不使用任何的字符串库

#include <iostream>#include <cassert>#include <cstring>using namespace std;int _strcmp(const char* s1, const char* s2) {    assert(s1 != NULL && s2 != NULL);    while (*s1 != '\0' && *s2 != '\0' && *s1 == *s2) {        s1++;        s2++;    }    if (*s1 > *s2) {        return 1;    }    else if (*s1 < *s2) {        return -1;    }    else {        return 0;    }}int main() {    char* s1 = "123";    char* s2 = "1234";    char* s3 = "123";    char* s4 = "234";    cout << _strcmp(s1, s2) << endl;    cout << _strcmp(s2, s1) << endl;    cout << _strcmp(s3, s1) << endl;    cout << _strcmp(s4, s2) << endl;    cout << endl;    cout << strcmp(s1, s2) << endl;    cout << strcmp(s2, s1) << endl;    cout << strcmp(s3, s1) << endl;    cout << strcmp(s4, s2) << endl;}

输出结果:
-1
1
0
1

-1
1
0
1

0 0
原创粉丝点击