解题思路:
这里提供一个不用比较函数的字符串比较的方法:利用C++string里重载的不等号直接对字符串进行比较
首先直接用string进行定义两个字符串,C++中string在头文件#include<string>中,也可以直接使用C++里的万能头文件#include<bits/stdc++.h>
string封装了字符串的储存和管理,并且可以自动处理字符串的储存和分配(这点让我们不用手动为字符串分配空间,十分方便)
string里也封装了字符串大小的比较,比较规则按字典序进行,所以可以直接进行str1>str2
if(str1>str2)cout<<1;
如果字符串str1大于str2则输出1
故代码可以用大于号小于号直接完成,代码示例如下:
参考代码:
#include<bits/stdc++.h> using namespace std; int main() {ios::sync_with_stdio(0),cin.tie(0),cout.tie(0); string str1; string str2; cin>>str1>>str2; if(str1>str2) cout<<1; else if(str1<str2)cout<<-1; else cout<<0; return 0; }
0.0分
1 人评分