作为标题,我想检查是否在另一个字符串中找到了子字符串。
#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变量的第一个字符与pattern变量进行比较,举个例子:
假设我们在文本变量中使用“ TEXT”,在模式中使用“ EX”:
在这种情况下,我开始将T与E进行比较。
我指向E并再次比较,有一个匹配项。
由于匹配,我在模式中指向X并在文本中执行相同操作,然后进行另一项测试。
第二次匹配,因此pattern变量中的字符数将与ct变量相同,而ct变量仅在匹配时才计数。
因此,收益应等于1。
代码始终返回零。我不明白为什么?
答案 0 :(得分:0)
CreateDirectoryEntry()
这是有问题的第一个循环,因为如注释部分所述,它将变量模式完全更改为空,因此没有可比较的内容。这段代码可以正常工作。
答案 1 :(得分:0)
假设,这是一个作业问题,或者您正在学习考虑针对入门者的此修订版:
int isIncluded ( char *text, char *pattern ); /* this is ok */
/*
can also write it this way
int isIncluded ( char text[], char pattern[] );
*/
int main ( void )
{
char text[30];
char pattern[30];
int result;
printf(" Please introduce your text \n");
scanf("%s", text); /* don't use &text here */
printf(" Please introduce the pattern you are looking for \n");
scanf("%s", pattern); /* don't use &pattern here */
/* don't pass a pointer to a pointer, the strings text and pattern are already pointers, you passing &text would mean isIncluded( char **text ) */
result = isIncluded( text, pattern );
if ( result == 1 )
{
printf(" Your pattern has been found in your text \n " ) ;
}
else if ( result == 0 )
{
printf(" no substring found \n " ) ;
}
else
{
/* don't overlook possibilities of missing simple stuff by not making use of else with if statements */
printf(" Error: value of result is %d\n", result );
}
}
我还没有研究为什么isIncluded
总是返回零,但是将指针传递给指向它的指针没有帮助。
如果您很好,也许我会写一些代码来开始您的学习,
但是您想做的事已经由strstr()
# include <string.h>
完全完成了
此外,定义 char text[30]
与定义用于键入字符的指针(称为文本)的功能相同,但此外它还保留了用于保存[n]的内存空间您说是30个字符。在这种情况下,除了做{{1}时实际发生的事情之外,了解定义和声明之间的区别可能会有所帮助}和text[3]
两者都是有效,明确且做相同的事情。
答案 2 :(得分:-3)
首先在您的isIncluded
函数中计算pattern
的长度,然后更改pattern
,然后又不是第一个,您可以使用诸如{{1} },但如果要使用这种方式进行计算,则应将新变量创建为strlen
,然后更改temp
变量。
在第二个while循环中模式结束的情况下,此函数的另一个问题应使用temp
而不是*pattern != '\0'
当您要调用函数pattern != '\0'
的参数并且有字符数组时,应该发送数组,并且char*
的类型为&text
最后是您想要的:
char**