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



我有一个赋值,用户在一个函数中输入一个字符串,然后输入一个模式,然后必须检查该模式是否存在于字符串中,以及它出现的次数和偏移量。我被难住了,我的同学不停地给我暗示。下面是我的获取功能

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("%sn", 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("%sn", 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();
}

我不知道该如何启动我的检查功能。更不用说我必须用指针通过引用,我也被卡住了

由于您要求提供模式匹配函数,我没有检查您的字符串输入函数。你可以使用这个简单的驱动程序代码来测试我的解决方案:

#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] != '')
{
// 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] != '' && 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] == '')
{
// 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);

您可能对解决方案考虑过度。您有一个字符串input,其中包含多个字符,您想计算其中pattern的多字符匹配数。字符串的一个好处是,您不需要知道它们的迭代长度,因为根据定义,C中的字符串以nul结束字符。

这使您可以简单地在findpattern函数中保留一个索引,并在每次input中的字符与pattern中的字符匹配时递增索引(否则将索引清零(。如果你达到pattern[index] == ''的点,你已经匹配了你模式中的所有字符。

您必须始终声明一个类型的函数,该函数将提供一个有意义的返回,以指示该函数执行的任何操作的成功/失败(如果该函数只是打印输出,则void可以(。

否则,您需要选择一个合理的返回类型来指示在input中是否找到(以及有多少(pattern的匹配。在这里,一个简单的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 */
idx = 0;                /* zero index for next match */
}
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(验证是否找到匹配项;以及(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 */
idx = 0;                /* zero index for next match */
}
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

所有相同的模式:

$ ./bin/findpattern my "mymymy"
'my' occurs 3 time(s) in 'mymymy'

功能本身的输出

虽然最好提供一个返回来指示匹配的数量(这将允许函数以多种不同的方式重用(,但如果您只是想将其作为一个输出函数,每次调用时都会输出结果,那么只需将输出移动到函数中,并声明另一个指向input的指针,这样input就可以保留下来,以便在最后打印。

变化很小,例如

#include <stdio.h>
void findpattern (const char *input, const char *ptrn)
{
const char *p = input;          /* pointer to input */
int n = 0, idx = 0;             /* match count and pattern index */
while (*p) {                    /* loop over each char in s */
if (*p == 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 */
idx = 0;                /* zero index for next match */
}
p++;                        /* increment pointer */
}
if (n)  /* output results */
printf ("'%s' occurs %d time(s) in '%s'n", ptrn, n, input);
else
puts ("pattern not found");
}
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";
findpattern (input, pattern);
}

(使用和输出同上(

仔细看看,如果你还有问题,请告诉我。

最新更新