【发布时间】:2018-12-11 16:59:54
【问题描述】:
正如标题中提到的,我想检查一个子字符串是否找到了另一个字符串。
#include <stdio.h>
#include <stdlib.h>
int isIncluded(char *text, char* pattern);
int main()
{
char text[30];
char pattern[30]; int result;
printf(" Please introduce your text \n");
scanf("%s", &text);
printf(" Please introduce the pattern you are looking for \n");
scanf("%s", &pattern);
result = isIncluded( &text, &pattern);
if ( result == 1)
{
printf(" Your pattern has been found in your text \n " ) ;
}
if ( result == 0)
{
printf(" no substring found \n " ) ;
}
}
int isIncluded(char *text, char* pattern)
{
int ct = 0;
int numberofcharacters = 0;
while ( *pattern != '\0')
{
pattern++;
numberofcharacters++;
}
while ( *text != '\0' && pattern != '\0')
{
if ( *pattern == *text)
{
pattern++;
ct++;
text++;
}
else
{
text++;
}
}
if ( ct == numberofcharacters )
{
return(1);
}
else
{
return(0);
}
}
思路是将文本变量的第一个字符与模式变量进行比较,举个例子:
假设我们在文本变量中有“TEXT”,在模式中有“EX”:
我开始比较T和E,在这种情况下,不匹配。
我指向 E 并再次比较,有一个匹配。
由于匹配,我在pattern中指向X并在文本中做同样的事情,然后我再做一次测试。
第2次匹配,因此pattern变量中的字符数将与ct变量相同,只有匹配时才计算。
因此返回应该等于1。
代码总是返回零。我不明白为什么?
【问题讨论】:
-
C 标准库附带
strstr()(<string.h>中的原型),它可以满足您的需求:) -
您的
pattern在isIncluded的第一个循环之后就被丢弃了... -
test是一个 char 数组和 数组名 本身的地址,因此scanf("%s", &text);-->scanf("%s", text);同样适用于pattern。 -
我认为您应该在调试器中单步执行您的函数,并检查它是否真的按照您的意愿/您认为的那样。
-
现在我正在发现有趣的调试工具,尝试逐步修复。当我更正我的程序时,我会发布它。