字符串比较差异(适用于某些情况,有时无效)

String Comparison Discrepancy (Works for some cases and sometimes doesn't)

我使用以下代码来测试我收到的电子邮件文件中的一些文本检测。

#include <stdio.h>

int main()
{
  int max_size = 100;
  char email[100] ="aheanstring4strinstringzil.comg";
  int pointer = 0;
  int i = 1;
  int j = 0;
  int len = 0;
  int chk = 0;
  char found1[7] = "string1";
  char found2[7] = "string2";
  char found3[7] = "string3";
  char found4[7] = "string4";
  char found5[7] = "string5";

  char user1[7] = "string1"; // 23        
  char user2[7] = "string2";// 19        
  char user3[7] = "string3"; // 14        
  char user4[7] = "string4"; // 16      
  char user5[7] = "string5";; // 15

  while (pointer != max_size && chk != 1)
  {

    for (j = 0;j<7; j++)
    {
      found1[j] = *(email+pointer+j);
    }

    if (strcmp(found1, user1) == 0){
      printf("Authorized User Found\n");
      chk = 1;
      continue;
    }

    for (j = 0;j<7; j++)
    {
      found2[j] = *(email+pointer+j);
    }

    if (strcmp(found2, user2) == 0){
      printf("Authorized User Found\n");
      chk = 1;
      continue;
    }

    for (j = 0;j<7; j++)
    {
      found3[j] = *(email+pointer+j);
    }

    if (strcmp(found3, user3) == 0){
      printf("Authorized User Found\n");
      chk = 1;
      continue;
    }

    for (j = 0;j<7; j++)
    {
      found4[j] = *(email+pointer+j);
    }

    if (strcmp(found4, user4) == 0){
      printf("Authorized User Found\n");
      chk = 1;
      continue;
    }


    for (j = 0;j<7; j++)
    {
      found5[j] = *(email+pointer+j);
    }

    if (strcmp(found5, user5) == 0){
      printf("Authorized User Found\n");
      chk = 1;
      continue;
    }

    pointer++;

  }
  printf("Check is %d, Pointer is %d\n",chk, pointer);
  return 0;
}

我使用上面的代码在电子邮件正文中查找特定用户。如果找到用户,while 循环就会中断。当我尝试 运行 时,我在上面的变量 (email)

中包含了不同的字符串

我首先在不同的在线 C 编译器上尝试 运行。他们所有人的字符串 1、3 和 5 都工作正常。 (正在检测)

其中一些字符串 2 工作正常(被检测到)。

然而,所有这些人都认为 string2 从未被检测到。我不知道为什么。我试着想了一个原因,但想不通。

非常感谢您的帮助。

char found1[7] = "string1";

此处 found1 不是 C 中的有效字符串,因为没有 nul 终止符。你需要

char found1[8] = "string1";

您将 found1 传递给 strcmp(),这将导致未定义的行为,因为 strcmp() 需要一个空终止字符串。

@Barak Manos建议你可以去

char found1[] = "string1";