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

时间:2015-06-04 08:46:58

标签: c arrays string pointers strcmp

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

#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循环中断。当我尝试运行它时,我在上面的变量(电子邮件)中包含了不同的字符串

我尝试在不同的在线C编译器上运行它。所有人都有1,3和5的字符串正常工作。 (被发现)

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

然而,他们都分享了从未检测到string2的事实。我不知道为什么。我试着考虑一个原因,但无法弄清楚原因。

我真的很感激一些帮助。

1 个答案:

答案 0 :(得分:3)

mfp stop

此处char found1[7] = "string1"; 不是C中的有效字符串,因为没有nul终止。你需要

found1

您将char found1[8] = "string1"; 传递给found1,这将导致未定义的行为,因为strcmp()期望一个空终止的字符串。

@Barak Manos 建议你可以选择

strcmp()