资源限制
时间限制:1.0s 内存限制:256.0MB
在C语言中,有一个strcmp函数,其功能是比较两个字符串s1和s2。请编写一个你自己的字符串比较函数my_strcmp,来实现strcmp函数的类似功能。如果s1=s2,则返回0;否则返回s1 与s2 第一个不同字符的差值(如果s1<s2,该差值是一个负数;如果s1>s2,该差值是一个正数)。编写测试程序,输入两个长度小于1000的字符串(可能包含有空格,且长度不一定相等),然后调用my_strcmp函数来进行比较,并输出返回结果。
输入:
aBcDefgf
aacdef
输出:
-31
#include<iostream>
//#include<bits/stdc++.h>
using namespace std;
int my_strcmp(char *s1,char *s2)
{
int x = 0;
int i;
for (i = 0; s1[i] != '\0' && s2[i] != '\0';i++)//循环判断,直到一个数组到达'\0'
{
x = s1[i] - s2[i];
if(x!=0)//求出了大小
break;
}
if(s1[i]!='\0'||s2[i]!='\0')//任意一个数组还没到'\0'
{
x = s1[i] - s2[i];
}
return x;
}
int main()
{
char s1[1000];
char s2[1000];
gets(s1);
gets(s2);
int x=my_strcmp(s1, s2);//调用函数
cout << x << endl;
system("pause");
return 0;
}