C子串两个相等的字符不匹配

时间:2014-11-25 19:31:06

标签: c

我正在编写一个程序来查找字符串中的子字符串。出于某些奇怪的原因,在将一个字符与另一个字符进行比较时,两个相似的字符不匹配。我不确定这是不是某种错误。 这是代码:

#include <stdio.h>
int first_char_compare(char *str,char a);

int main()
{
    int i,j, char_exists,substring;
    char string1[] = "jrsfahamfsf";
    char string2[] = "ham";

    char_exists = first_char_compare(string1,string2[0]);


    if(!(char_exists<0))
    {
        j=char_exists;

        for(i=0;string2[i]!='\0';i++)
        {
            for(;string1[j]!='\0';j++)
            {
                printf("%c\t%c\n",string2[i],string1[j]);
                if(string1[i]==string2[j])
                {
                    substring = 1;
                    printf("matches\n");
                    break;
                }
                else
                {
                    printf("doesn't match\n");
                    substring = 0;
                }
            }

            if(substring==0)
                break;

            j++;
        }

    }

    if(substring)
        printf("Is a substring\n");
    else
        printf("Not a substring\n");

    return 0;
}


int first_char_compare(char *str,char a)
{
/* Checks if the first character of the substring is in the main string.
 * If the character exists, it's index is returned. If it doesn't exist
 * -1 is returned.
 */
    int i;
    for(i=0;str[i]!='\0';i++)
    {
        if(a==str[i])
            return i;
    }
    return -1;
}

1 个答案:

答案 0 :(得分:2)

在您的循环中,string2i索引,string1j索引:

for (i = 0; string2[i] != '\0'; i++)
{
  for( ; string1[j] != '\0'; j++)
  {

但在你的比较中,指数是倒退的:

if (string1[i] == string2[j])

更正:

if (string1[j] == string2[i])