字符串检查不返回值

时间:2013-10-16 02:20:08

标签: c string substring

程序应该读入用户想要的任何输入(在这种情况下只是一个字符串的a和b)以“*”结尾,然后它会提示用户输入他们想要搜索的子字符串(在这种情况下为“baab”) “)。如果找到子字符串,则程序指示是,否则如果未找到则表示否。我不被允许使用内置的匹配实用程序,它必须一次读取一个字符。

我刚用scanf替换了gets(),现在当我输入我的子字符串并确定它匹配时它仍然说不是吗?

#include<stdio.h>
#include<string.h>
int search(char[], char[]);

int main()
{
    char a[100], b[40];
    int loc;

    printf("Enter the main string :");
    scanf("%s", a);
    printf("Enter the search string :");
    scanf("%s", b);

    loc = search(a, b);

    if (loc == -1)
        printf("No");
    else
        printf("Yes %d", loc + 1);

    return (0);
}

int search(char a[], char b[])
{
    int i, j, firstOcc;

    i = 0, j = 0;

    while (a[i] != '*')
    {
        while (a[i] != b[0] && a[i] != '*')
            i++;
        if (a[i] == '*')
            return (-1);

        firstOcc = i;

        while (a[i] == b[j] && a[i] != '*' && b[j] != '*')
        {
            i++;
            j++;
        }

        if (b[j] == '*')
            return (firstOcc);
        if (a[i] == '*')
            return (-1);

        i = firstOcc + 1;
        j = 0;
    }
}

1 个答案:

答案 0 :(得分:0)

您还需要使用*终止第二个字符串 - 然后事情正确匹配。实际上,你的代码一直在匹配“一个字符太多” - 并且在b字符串的末尾找到了不匹配的'\ 0'。

如果您不希望在b字符串的末尾加上星号,则不得编写需要它的代码...您可以按如下方式修改代码(我输入了充足的printf语句所以你可以看到发生了什么。注意 - 我将修复程序保留为gets作为练习。真的,拜托。解决它。

include <stdio.h>

int search(char a[], char b[]);

int main()
{
    char a[100], b[40];
    int loc;

    printf("Enter the main string terminated with '*':");
    gets(a); // please don't...

    printf("Enter the search string :");
    gets(b);

    loc = search(a, b);

    if (loc == -1)
        printf("No");
    else
        printf("Yes %d", loc + 1);

    return (0);
}

int search(char a[], char b[])
{
    int i = 0, j = 0, lenB, firstOcc;

    for(lenB=0; b[lenB]!='\0';lenB++);

    printf("a is %s\n", a);
    while (a[i] != '*')
    {
        printf("i = %d\n", i);
        while (a[i] != b[0] && a[i] != '*')
            i++;
        if (a[i] == '*')
            return (-1);
        printf("matching a[i]=%c and b[0]=%c\n", a[i], b[0]);

        firstOcc = i;

        while (a[i] == b[j] && a[i] != '*' && j < lenB)
        {
            printf("a[%d] matches b[%d]\n", i, j);
            i++;
            j++;
        }

        if (j == lenB)
            return (firstOcc);
        if (a[i] == '*')
            return (-1);

        i = firstOcc + 1;
        j = 0;
        printf("going to take another look with i=%d and j=%d\n", i, j);
    }
}