我有一个字符串结构.
struct string
{
char *c;
int length;
int maxLength;
}
Run Code Online (Sandbox Code Playgroud)
我想检查两个字符串是否相等.
所以我想运行一个for循环.
for(int i = 0; i < length; i++)
if(s1[i] != s2[i]) // This code is more C# than C.
Run Code Online (Sandbox Code Playgroud)
s1和s2都是字符串结构.
我该怎么办if(s1[i] != s2[i])?
编辑: 我刚刚做了这个,是不是杀了?
for(i = 0; i < length; i++)
if((*s1).c[i] != (*s2).c[i])
{
printf("Failed");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
假设您可以使用带有\0终止的C字符串,我会这样做并使用strcmp:
if (strcmp(s1.c, s2.c)) {
// action if strings are not equal
}
Run Code Online (Sandbox Code Playgroud)
我假设您想自己编写比较代码,而不是使用内置函数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]);
}
Run Code Online (Sandbox Code Playgroud)
该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
}
Run Code Online (Sandbox Code Playgroud)
代码的两个版本假设在字符串s1->c和s2->c为空值终止,并且s1->length == strlen(s1->c)和s2->length == strlen(s2->c).
与C99,它也将是可能的使用_Bool作为返回类型,或<stdbool.h>和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;
}
Run Code Online (Sandbox Code Playgroud)