题解 | #比较字符串大小#
比较字符串大小
https://www.nowcoder.com/practice/963e455fdf7c4a4a997160abedc1951b
#include <iostream>
#include <cstring>
using namespace std;
int mystrcmp(const char* src, const char* dst);
int main() {
char s1[100] = { 0 };
char s2[100] = { 0 };
cin.getline(s1, sizeof(s1));
cin.getline(s2, sizeof(s2));
int ret = mystrcmp(s1, s2);
cout << ret << endl;
return 0;
}
int mystrcmp(const char* src, const char* dst) {
// write your code here......
//计算src和dst长度
int len1 = strlen(src);
int len2 = strlen(dst);
int i = 0, j = 0;
while (i < len1 && j < len2) {
//如果src当前字符小于dst,说明src小于dst,返回-1
if (src[i] < dst[j]) {
return -1;
}
//如果src当前字符大于dst,说明src大于dst,返回1
else if (src[i] > dst[j]) {
return 1;
}
//如果src当前字符等于dst,两指针后移
else {
i++;
j++;
}
}
//如果src后面还有字符,返回1。说明src还没完,dst已经完了
if (i < len1) {
return 1;
}
//如果dst后面还有字符,返回-1。说明src已经完了
else if (j < len2) {
return -1;
} else {
return 0;
}
return 0;
}
