[C++]蓝桥杯 ADV-95. 字符串比较

独⽴实现标准字符串库的strcmp函数,即字符串⽐较函数,从键盘输⼊两个字符串,按字典序⽐较⼤⼩,前者⼤于后者输出1,前者⼩于后者输出-1,两者相等输出0。
样例输⼊:
apple one
样例输出:
-1
样例输⼊:
hello he
样例输出:
1
样例输⼊:
hello hello
样例输出:
0

#include <iostream>
using namespace std;
int main() {
 string a, b;
 cin >> a >> b;
 int lena = a.length();
 int lenb = b.length();
 int len = lena > lenb ? lena : lenb;
 for(int i = 0; i < len; i++) {
 if(a[i] > b[i]) {
 cout << "1";
 return 0;
 }
 if(a[i] < b[i]) {
 cout << "-1";
 return 0;
 }
 }
 if(lena == lenb) {
 cout << "0";
 } else if(lena > lenb) {
 cout << "1";
 }else {
 cout << "-1";
 }
 return 0;
}
发布了87 篇原创文章 · 获赞 15 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_43356428/article/details/104933576
今日推荐