问题描述
自己实现一个比较字符串大小的函数,也即实现strcmp函数。函数:int myStrcmp(char *s1,char *s2) 按照ASCII顺序比较字符串s1与s2。若s1与s2相等返回0,s1>s2返回1,s1<s2返回-1。具体来说,两个字符串自左向右逐个字符相比(按ASCII值大小相比较),直到出现不同的字符或遇'\0'为止(注意'\0'值为0,小于任意ASCII字符)。如:
"A"<"B"
"a">"A"
"computer">"compare"
"hello"<"helloworld"
样例输出
数据规模和约定
字符串长度<100。
1 #include <iostream>
2 #include <algorithm>
3 #include <cstdio>
4 #include <cmath>
5 #include <stack>
6 #include <queue>
7 using namespace std;
8 int main()
9 {
10 string s1,s2;
11 while(cin>>s1>>s2){
12 int len1=s1.length();
13 int len2=s2.length();
14 int len=len1<len2?len1:len2;
15 //cout<<len<<endl;
16 int flag=0;
17 for(int i=0;i<len;i++){
18 if(s1[i]>s2[i]){
19 flag=1;
20 break;
21 }else if(s1[i]<s2[i]){
22 flag=-1;
23 break;
24 }
25 }
26 if(len1>len2) flag=1;
27 else if(len1<len2) flag=-1;
28 cout<<flag<<endl;
29 }
30 return 0;
31 }