我的任务是编写一个程序来计算一个字符序列在另一个字符序列中出现的次数。 “模式”函数应返回第一个序列在第二个序列中出现的次数而不重复。由于这是一个编程练习,我不允许使用括号来取消引用指针,而只能使用指针算术。
我决定使用 if
语句来查看数组中是否出现序列。我很难看出我的问题在哪里。我打印出 pValue1
以查看指针在数组中的位置。任何帮助将不胜感激。
#include <stdio.h>
#include <string.h>
int pattern(char *ptr1, char *ptr2)
{
char *pValue1 = ptr1;
char *pValue2 = ptr2;
int count = 0;
int occurrence = 0;
while (*pValue1 != '\0')
{
if (*pValue1 == *pValue2)
{
if (*pValue1++ == *pValue2++)
{
if (*pValue1 + 2 == *pValue2 + 2)
{
printf("Occurence happens at Location: %d", count);
occurrence++;
}
}
}
count++;
pValue1 = pValue1 + count;
printf("%d", pValue1);
}
/* Print number of occurrences. */
printf("number of occurrences: %i \n", occurrence);
}
void main()
{
char array1[] = "1','1','0','1','0','0','1','1','1','0','1','1','\0'";
char array2[] = "'1','0', '1', '\0'";
pattern(array1, array2);
getchar();
getchar();
}
最佳答案
您的比较代码相当困惑。此行可能没有按照您的预期执行:
if (*pValue1 + 2 == *pValue2 + 2)
它解引用每个指针,然后将结果加 2。我觉得你 打算这样做:
if (*(pValue1 + 2) == *(pValue2 + 2))
以此为本意,代码还是错误的。首先,你比较 [0] 处的字符:
if (*pValue1 == *pValue2)
然后递增指针,并比较 [1] 处的字符:
if (*pValue1++ == *pValue2++)
然后检查 [3] 处的字符:
if (*(pValue1 + 2) == *(pValue2 + 2))
因此,您跳过了 [2],并且您只检查了几个字符。你 需要一个循环来检查第一个字符串中的所有内容 您正在检查第二个字符串。
此外,您似乎正在调用 pattern()
来检查整个秒
字符串?但是你只是在检查它的开头。你需要一个
外循环遍历第二个字符串的每个部分。
main()
的第一行通常这样写:
char array1[] = "110100111011";
char array2[] = "101";
我还建议将参数重命名为 needle
和 haystack
,以
使代码更具可读性。
关于c - 数组中的模式出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33577644/