c语言字符数组内容比较,比较C中的两个字符数组

Jonathan Lef..

6

我假设您想自己编写比较代码,而不是使用内置函数strcmp()- 这可能是通过编写提升的性能,或者生成为优化的汇编程序代码.该are_equal()函数将返回1(真)如果字符串相等0(假),否则.

次优解决方案

static inline int min(int a, int b) { return (a < b) ? a : b; }

int are_equal(const struct string *s1, const struct string *s2)

{

int len = min(s1->length, s2->length);

int i;

for (i = 0; i < len; i++)

{

if (s1->c[i] != s2->c[i])

return 0; // They are different

}

return(s1->c[i] == s2->c[i]);

}

该inline函数假定为C99编译器; 如果您使用C89卡住,可以用适当的宏替换它.

更接近最优解决方案

int are_equal(const struct string *s1, const struct string *s2)

{

if (s1->length != s2->length)

return 0; // They must be different

for (int i = 0; i < s1->length; i++)

{

if (s1->c[i] != s2->c[i])

return 0; // They are different

}

return 1; // They must be the same

}

代码的两个版本假设在字符串s1->c和s2->c为空值终止,并且s1->length == strlen(s1->c)和s2->length == strlen(s2->c).

与C99,它也将是可能的使用_Bool作为返回类型,或和bool(作为返回值类型)和true与false作为返回值.

使用替代解决方案 strcmp()

请注意,如果您只是使用strcmp(),如果字符串相等,您将获得0,如果字符串不相等,则将获得非零值.所以,如果字符串相等,你也可以写这样的函数返回true,否则返回false:

int are_equal(const struct string *s1, const struct string *s2)

{

return strcmp(s1->c, s2->c) == 0;

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值