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;

}