如何检查输入的字符串中是否存在模式?

问题描述 投票:0回答:2

我有一个分配,用户在其中输入一个字符串,然后在一个函数中输入一个模式,然后必须检查该模式是否存在于字符串中,它出现了多少次以及偏移了多少。我很沮丧,我的同学不断给我一些神秘的提示。下面是我的get函数

int getNums()
{
    printf("Please enter a number: ");      //Initial printf

    int count, patcount;
    int torf;
    char len_num[31];       //The character array for the initial entered string
    char pat_num[6];        //The character array for the entered pattern after initial string
    char *lenptr = len_num;     //pointer to the address of the first element of len_num
    char *patptr = pat_num;     //pointer to the address of the first element of len_num

    scanf("%s", len_num);       //Where the user scans in their wanted number, which is treated as a string
    printf("\n");

    printf("%s\n", lenptr);
    int len = stringLength(lenptr);     //Checks how long string is
    int valid = isValid(len_num);       //Checks if string is valid


    for(count=0; count<len_num[count]; count++)     //Checks if length of string is within appropriate range
    {
        if(len>=10 && len<=30)      //Continues to pattern get if within range
        {
            torf=1;
        }

        else                        //Denies continuation if string is outside of range
        {
            torf=0;
            printf("Not within range! Try again!\n");
            return (1);
        }
    }

    printf("Please enter a pattern: ");     //Initial entry statement for pattern

    scanf("%s", pat_num);                   //User scans in pattern
    printf("\n");

    printf("%s\n", pat_num);
    len = stringPattern(patptr);            //Check how long pattern is
    valid = isValid(pat_num);               //Checks if pattern is valid

    for(patcount=0; patcount<pat_num[patcount]; patcount++) //Checks if length of pattern is within appropriate range
    {
        if(len>=2 && len<=5)                //Continues to pattern check if within range
        {
            torf=1;
        }

        else                                //Denies continuation if pattern is outside of range
        {
            torf=0;
            printf("Pattern not within range! Try again!\n");
            return (1);
        }
    }

    checkPattern();
}

我不知道如何启动检查功能。更不用说我必须通过引用传递指针,并且我也坚持这样做

c
2个回答
0
投票

由于您要求使用模式匹配功能,因此我没有检查您的字符串输入功能。您可以使用以下简单的驱动程序代码来测试我的解决方案:

#include <stdio.h>

void findPattern(char* input, char* pattern);

int main()
{
    char input[31], pattern[6];
    printf("Enter the string: ");
    scanf("%s", input);
    printf("Enter the pattern: ");
    scanf("%s", pattern);
    findPattern(input, pattern);
    return 0;
}

[findPattern胜过checkPattern。您应根据自己的方便将其重命名。根据您的要求,除stdio.h中的库函数外,我没有使用任何库函数。以下是我承担的这项任务,我在注释中解释了逻辑。基本上,它只遍历整个输入字符串一次,在此检查与模式中的初始字符是否匹配。如果是这样,它将标记偏移量并在模式中进一步搜索以找到完全匹配。

void findPattern(char* input, char* pattern)
{
    int i = 0; // iterator for input
    int j = 0; // iterator for pattern

    // solution variables
    int offset = 0;
    int occurrence = 0;

    // Search the entire input string
    while (input[i] != '\0')
    {
        // Mark the offset whenever the first character of the pattern matches
        if (input[i] == pattern[j])
        {
            offset = i;
            // I didn't quite get the relativity of your offset
            // Maybe you need: offset = i + 1;
        }

        // Search for complete pattern match
        while (input[i] != '\0' && pattern[j] == input[i])
        {
            // Go for the next character in the pattern
            ++j;

            // The pattern matched successfully if the entire pattern was searched
            if (pattern[j] == '\0')
            {
                // Display the offset
                printf("\nPattern found at offset %d", offset);

                // Increment the occurrence
                ++occurrence;

                // There are no more characters left in the pattern
                break;
            }
            else
            {
                // Go for the next character in the input
                // only if there are more characters left to be searched in the pattern
                ++i;
            }
        }

        // Reset the pattern iterator to search for a new match
        j = 0;

        // Increment the input iterator to search further down the string
        ++i;
    }

    // Display the occurrence of the pattern in the input string
    printf("\nThe pattern has occurred %d times in the given string", occurrence);
}

我必须通过引用传递指针,但我也坚持这样做

如果是这种情况,请以findPattern(input, pattern);代替:

findPattern(&input, &pattern);


0
投票

您可能会想不通解决方案。您有一个字符串input,其中包含许多字符,您想计算其中的pattern多字符匹配数。关于字符串的一件好事是,您不需要知道它们要迭代多长时间。 ,因为根据定义,C中的字符串以nul-terminated字符结尾。

这可以让您简单地将索引保留在findpattern函数中,并且每次input中的字符与pattern中的字符匹配时都可以增加索引(否则将索引清零)。如果到达pattern[index] == '\0'的位置,则表示您已匹配模式中的所有字符。

您必须始终使用type声明一个函数,如果需要其余代码,则该有意义的返回值将指示该函数执行的任何操作的成功/失败(如果该函数仅打印输出) -那么void就可以了)。

否则,您需要选择一个合理的返回类型以指示在pattern中是否找到input匹配项(以及匹配多少)。在这里,简单的int类型即可。 (这限制了可以返回2147483647的匹配数,应该足够了。

将这些部分放在一起,您可以将功能简化为类似于:

int findpattern (const char *input, const char *ptrn)
{
    int n = 0, idx = 0;             /* match count and pattern index */

    while (*input) {                /* loop over each char in s */
        if (*input == ptrn[idx])    /* if current matches pattern char */
            idx++;                  /* increment pattern index */
        else    /* otherwize */
            idx = 0;                /* zero pattern index */
        if (!ptrn[idx])             /* if end of pattern - match found */
            n++;                    /* increment match count */
        input++;                    /* increment pointer */
    }

    return n;                       /* return match count */
}

添加一个简短的示例程序,该程序允许您将patterninput输入为程序的前两个参数(或使用未显示的默认值);

int main (int argc, char **argv) {

    char  *pattern = argc > 1 ? argv[1] : "my",
            *input = argc > 2 ? argv[2] : "my dog has fleas, my cat has none";
    int n;

    if ((n = findpattern (input, pattern)))
        printf ("'%s' occurs %d time(s) in '%s'\n", pattern, n, input);
    else
        puts ("pattern not found");
}

注意提供有意义的回报如何使您同时(1)validate是否找到匹配项; (2)提供通过返回找到的匹配数。完整的代码只需要标题stdio.h,例如

#include <stdio.h>

int findpattern (const char *input, const char *ptrn)
{
    int n = 0, idx = 0;             /* match count and pattern index */

    while (*input) {                /* loop over each char in s */
        if (*input == ptrn[idx])    /* if current matches pattern char */
            idx++;                  /* increment pattern index */
        else    /* otherwize */
            idx = 0;                /* zero pattern index */
        if (!ptrn[idx])             /* if end of pattern - match found */
            n++;                    /* increment match count */
        input++;                    /* increment pointer */
    }

    return n;                       /* return match count */
}

int main (int argc, char **argv) {

    char  *pattern = argc > 1 ? argv[1] : "my",
            *input = argc > 2 ? argv[2] : "my dog has fleas, my cat has none";
    int n;

    if ((n = findpattern (input, pattern)))
        printf ("'%s' occurs %d time(s) in '%s'\n", pattern, n, input);
    else
        puts ("pattern not found");
}

示例使用/输出

检查多个匹配项:

$ ./bin/findpattern
'my' occurs 2 time(s) in 'my dog has fleas, my cat has none'

单场比赛:

$ ./bin/findpattern fleas
'fleas' occurs 1 time(s) in 'my dog has fleas, my cat has none'

未找到模式

$ ./bin/findpattern gophers
pattern not found

仔细检查,如果还有其他问题,请告诉我。

© www.soinside.com 2019 - 2024. All rights reserved.