/************************************************************************/
/*
1、 不使用库函数,编写函数int strcmp(char *source, char *dest)
相等返回0,不等返回-1; */
/************************************************************************/
方法一://
#include <iostream>
using namespace std;
int strcmp0(char *source ,char *dest)
{
int i=0,j=0;
while(source[i]!=NULL)
{
i++;
} //cout<<i<<endl;
while(dest[j]!=NULL)
{
j++;
} //cout<<j<<endl;
if(i!=j)
return -1;
for(int k=0;k<i;k++)
{
if(source[k]!=dest[k])
return -1;
}
return 0;
}
此方法中求长度的循环可以用函数strlen来代替就变得简单多了,即:
int strcmp0(char *source ,char *dest)
{
if(strlen(source)!=strlen(dest))
return -1;
for(int k=0;k<strlen(source);k++)
{
if(source[k]!=dest[k])
return -1;
}
return 0;
}
方法二:
#include <iostream>
#include <assert.h>
#include <string.h>
using namespace std;
int strcmp(char *source, char *dest)
{
int i;
assert((NULL != source)&&(NULL != dest));
if(strlen(source) != strlen(dest))
return -1;
for(i = 0;i < strlen(source);i++)
{
if(*(source + i) != *(dest + i))
return -1;
}
return 0;
};