java比较字符串函数_C中的字符串比较函数有什么问题?如何比较字符串?

我昨天在接受采访时被要求编写一个函数来比较两个字符串,基本上与strcmp()的输出相同 . 我编写了以下程序和compare()函数,但被告知错了 . 采访者说,“你比较字符串从低字节到高字节 . 如果发生string1具有较小的较低字节但更高的字节,你的代码将输出string1小于字符串2,这是错误的 . ”

我想当我们进行字符串比较时,我们从左到右比较两个字符串,并将每对相应的字符与它们的ASCII值进行比较 . 我还找到了strcmp()的一些源代码,并尝试了很多案例来比较我的结果和strcmp()的结果,所以我认为该程序是正确的 .

我把我的程序写在这里的面试中 . 为了比较,我打印了我写的函数和strcmp()的值 . 我不得不说它不是很简洁 .

#include

#include

#include

int compare (char *string1, char *string2, int length1, int length2);

int main()

{

int len1,len2;

char *str1;

char *str2;

int result;

int result1;

//Input the string1

printf("Please input the length of string1\n");

scanf("%d", &len1);

str1=malloc(sizeof(char)*len1);

printf("Please input string 1:\n");

scanf("%s",str1);

//Input the string2

printf("Please input the length of string2\n");

scanf("%d", &len2);

str2=malloc(sizeof(char)*len2);

printf("Please input string 2:\n");

scanf("%s",str2);

//Do comparison, Both compare() and strcmp() are used

result=compare(str1,str2,len1,len2);

result1=strcmp(str1,str2);

printf("\nThe result of compare() is: %d\n",result);

printf("The result of strcmp() is:%d\n",result1);

return 0;

}

int compare (char *string1, char *string2,int length1, int length2)

//If string1>string2, return1; if string1

{

int result=0;

// Use the shorter length to do comprison bit by bit

int length=(length1>length2)?length2:length1;

for(int i=0;i

{

if(string1[i]>string2[i])

{

result=1;

printf("%d\n",result);

break;

}

else if (string1[i]

{

result=-1;

printf("%d\n",result);

break;

}

}

if(result==1)

{

return 1;

}

else if (result==-1)

{

return -1;

}

else if (length1>length2)

{

return 1;

}

else if (length1

{

return -1;

}

else

{

return 0;

}

}

所以有人能告诉我程序中有什么问题吗?你能给我一个例子,比较compare()和strcmp()的结果是不一样的吗?

谢谢!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值