5

我有一个字符串结构。

struct string
{
   char *c;
   int length;
   int maxLength;
}

我想检查两个字符串是否相等。

所以我想运行一个for循环。

for(int i = 0; i < length; i++)
   if(s1[i] != s2[i]) // This code is more C# than C.

s1 和 s2 都是字符串结构。

我该怎么做if(s1[i] != s2[i])

编辑: 我刚做了这个,是不是杀过头了?

    for(i = 0; i < length; i++)
    if((*s1).c[i] != (*s2).c[i])
    {
        printf("Failed");
        return 0;
    }
4

5 回答 5

9

假设您可以使用带有\0终止的 C 字符串,我会这样做并使用strcmp

if (strcmp(s1.c, s2.c)) {
    // action if strings are not equal
}
于 2013-09-19T05:18:40.470 回答
6

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

次优解决方案

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->cands2->c中的字符串以空字符结尾,s1->length == strlen(s1->c)s2->length == strlen(s2->c).

在 C99 中,也可以将其_Bool用作返回类型,或者<stdbool.h>bool(作为返回类型)和truefalse作为返回值。

替代解决方案使用strcmp()

请注意,如果您简单地使用strcmp(),如果字符串相等,您将获得 0,如果字符串不相等,您将获得非零值。因此,您也可以编写这样的函数,如果字符串相等则返回 true,否则返回 false:

int are_equal(const struct string *s1, const struct string *s2)
{
    return strcmp(s1->c, s2->c) == 0;
}
于 2013-09-19T05:19:24.220 回答
3

您的if陈述不完整(可能缺少设置标志然后 abreak或 a return),并且您可能不使用structso

struct string {
  char *c;
  int length;
  int maxLength;
};

bool same_string (struct string *s1, struct string* s2) {
  int ln1 = s1->length;
  if (ln1 != s2->length) return false;
  for (int i=0; i<ln1; i++)
    if (s1->c[i] != s2[ci]) return false;
  return true;
}

但你真的strncmp想要

bool same_string (struct string *s1, struct string* s2) {
  if (s1->length != s2->length) return false;
  return strncmp(s1->c, s2->c, s1->length)==0;
}
于 2013-09-19T05:19:26.017 回答
1

您需要比较每个成员

int compare(struct string s1, struct string s2){

return (strcmp(s1.c,s2.c) == 0) && 
       (s1.maxLength ==s2.maxLength) &&
       (s1.length ==s2.length) ;
}

for(int i = 0; i < length; i++)
   if(!compare(s1,s2)) { 
  }
于 2013-09-19T05:18:59.263 回答
0

你真的不需要知道字符串的长度来比较它们。您可以最好使用标准库中的字符串比较工具strncmpover strcmp,或者您可以编写自己的类似这样的工具:

int strcmp(char *s1, char *s2)
{
  int i;
  for (i = 0; s1[i] == s2[i]; i++)
    if (s1[i] == '\0')
      return 0;
  return s1[i] - s2[i];
}
于 2013-09-19T05:21:47.203 回答