简体   繁体   English

为什么我的程序无法打印出正确的消息?

[英]Why isn't my program printing out the correct message?

I'm trying to write a program to see if string 1 is a part of string 2. At the command prompt, I enter string 1, and then string 2. But the problem is, no matter what I type, my program keeps printing out the answer that "No, string 1 is not a part of string 2". 我正在尝试编写程序以查看字符串1是否为字符串2的一部分。在命令提示符下,我输入字符串1,然后输入字符串2。但是问题是,无论我键入什么内容,我的程序都会继续打印回答“不,字符串1不是字符串2的一部分”。 I'm not sure what I could be doing wrong, is there something wrong with my for loop? 我不确定自己可能做错了什么,我的for循环有问题吗? Help is appreciated! 感谢帮助!

int string_part_of_other(void)
{
   char str1[20];
   char str2[20];
   int answer = 1;

   printf("Enter string 1:\n");
   scanf("%s", str1);

   printf("Enter string 2:\n");
   scanf("%s", str2);

   for (int i = 0; str1[i] != '\0'; i++)
   {
      for (int j = 0; str2[j] != '\0'; j++)
      {
         if (str1[i] != str2[j])
         {
            answer = 0;
         }
      }
   }

   return answer;
}

int main()
{
   int result;
   result = string_part_of_other();

   if (result == 1)
   {
      printf("Yes, string 1 is part of string 2.\n");
   }

   if (result == 0)
   {
      printf("No, string 1 is not part of string 2.\n");
   }

   return 0;
}

The problem is in your loop. 问题出在你的循环中。 You're comparing an entire string against one character. 您正在将整个字符串与一个字符进行比较。

for (int i = 0; str1[i] != '\0'; i++){
   for (int j = 0; str2[j] != '\0'; j++){ // here
      if (str1[i] != str2[j]) answer = 0; 
   }
}

strpbrk or strstr is a function that does this automatically, if that's what you would prefer. strpbrkstrstr是一个自动执行此功能的函数(如果您愿意)。

You could also try this: 您也可以尝试以下方法:

for (int i = 0; str1[i]; i++){
    int j = 0;
    for (; str2[j] && str1[i + j]; j++){
        if (str2[j] != str1[i + j]) break;
    }
    if (!str2[j]) return 1; /*
    * This means the loop broke because it reached the end of the
    * string, not because of a mismatch. Therefore, str2 is within str1
    */
}

return 0;

Also, I think it is your intention to say string 2 is part of string 1 , and not the other way around. 另外,我认为您打算说string 2 is part of string 1 ,而不是相反。

The algorithm you've written answers the following: 您编写的算法可以回答以下问题:

"For each character in string1, does it match every character in string2?" “对于string1中的每个字符,它是否匹配string2中的每个字符?”

If you step through the code in your head you should be able to figure out what's going wrong, and how to fix it. 如果您脑海中遍历代码,那么您应该能够找出问题所在以及解决方法。

Few remarks: 几句话:

  • don't use scanf() . 不要使用scanf() It doesn't do what you think it does, and it even goes unprotected without the ability to specify field width, so you should expect buffer overruns. 它没有做您想像的事情,并且甚至没有指定字段宽度的能力也变得不受保护,因此您应该期待缓冲区溢出。

  • so use fgets(buf, sizeof(buf), stdin) instead (and beware of trailing newlines). 因此请改用fgets(buf, sizeof(buf), stdin) (并注意尾随换行符)。

  • Don't reinvent the wheel: there's a function called strstr() in the C standard library which does exactly what you want, and it works correctly unlike your current ugly-hack-with-unreadable-nested-for-loops. 不要重新发明轮子:C标准库中有一个名为strstr()的函数,它可以完全满足您的要求,并且可以正常工作,这与您当前的丑陋,无法读取的嵌套循环不同。

All in all: 总而言之:

int part_of()
{
    char buf1[LINE_MAX], buf2[LINE_MAX], *p;
    fgets(buf1, sizeof(buf1), stdin);
    fgets(buf2, sizeof(buf2), stdin);

    p = strchr(buf1, '\n');
    if (p) *p = 0;
    p = strchr(buf2, '\n');
    if (p) *p = 0;

    return strstr(buf1, buf2) != NULL;
}

Also, don't write if (func() == 1) {} then if (func() == 0) {} immediately afterwards - redundancy is bad. 另外,之后不要立即写if (func() == 1) {}然后再写if (func() == 1) {} if (func() == 0) {} -冗余性很差。 if (func()) {} else {} is fine. if (func()) {} else {}很好。

For example, if your last char in str1 and last char in str2 do not match each other, the answer will be 0 . 例如,如果您在str1最后一个字符和在str2最后一个字符彼此不匹配,则answer将为0 Even if str2 is a part of str1 即使str2str1的一部分

you are just comparing all characters of str1 with that of str2 and even if one mismatch is there you set answer to zero .. wrong logic based on asked question I am assuming you want to check str1 to be a part of str2, the outer loop should be of the parent or containing string in this case str2 ... 您只是将str1的所有字符与str2的所有字符进行比较,即使存在一个不匹配,您也将答案设置为零..基于询问的错误逻辑我假设您要检查str1是否为str2的一部分,外循环在这种情况下应为父级或包含字符串str2 ...

    int answer=0;
    for(int i=0;str2[i]!='\0';i++) //traversing bigger string
    {
    if(str2[i]==str1[0])
    //if character of bigger string matches first  character small string
    {
    for(int j=0;str1[j]!='\0';j++)
    { 
    if(((i+j)<strlen(str2))&&(str1[j]!=str2[i+j])){
    break;}
    }//j
    if(str1[j-1]=='\0')
    {answer=1;
     break;}
    }//i
if (str1[i] != str2[j]) {
            answer = 0;
}

If the 1st literal in your string1 does not match with string2 answer is set to 0, after that even if you find the substring you are not changing answer to 1 so you are not getting the proper result. 如果string1中的第一个文字与string2不匹配,则答案设置为0,此后,即使您找到子字符串,也不会将答案更改为1,因此无法获得正确的结果。

Also you are just incrementing str2 index and not incrementing str1 index with it, so you will never find the string, so change the logic. 另外,您只是在增加str2索引,而不是在其中增加str1索引,因此您将永远找不到该字符串,因此请更改逻辑。

I rewrite some of your code: 我重写了一些代码:

#include <stdio.h>

int string_part_of_other(void)
{
   char str1[20];
   char str2[20];
   int answer = 0;
   int i, j, k;

   printf("Enter string 1:\n");
   scanf("%s", str1);

   printf("Enter string 2:\n");
   scanf("%s", str2);

   i = j = k =0;

   while(str2[j] !='\0')
   {
       k = j;
       for(i = 0; str1[i] != '\0' && str2[k] != '\0'; i++, k++)
       {
           if(str1[i] != str2[k])
           {
               break;
           }
       }

       if(str1[i] == '\0')
       {
           answer = 1;
       }
       j++;

   }

   return answer;
}

int main()
{
   int result;
   result = string_part_of_other();

   if (result == 1)
   {
      printf("Yes, string 1 is part of string 2.\n");
   }

   if (result == 0)
   {
      printf("No, string 1 is not part of string 2.\n");
   }

   return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM