问题描述
我正试图通过练习《 C语言编程》来发挥作用。正确的函数应指示一行是否包含某个单词,如果是,则返回该单词在该行中的第一个字符位置。
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
int substring (char a[],char b[]);
int main ()
{
char line1[15],line2[15];
printf("Print first one\n");
int i = 0;
char character;
do
{
character = getchar ();
line1[i] = character;
i++;
}
while (character != '\n');
line1[i-1] = '\0';
printf ("Print the second one\n");
scanf("%s",line2);
printf("%s,%s\n",line1,line2); \\ for checking lines
int index;
index = substring (line1,line2);
printf("The result is: %i\n",index);
}
int substring (char a[],char b[])\*function to determine if a line contains a word,if yes then return its polition,else return -3*\
{
int len1 = strlen(a),len2 = strlen(b);
int current1 = 0,current2 = 0;
bool found = false;
int result;
while( current1 < len1 )
{
if (a[current1] == b[current2])
{
if(!found)
{
result = current1+1;
}
else
found = true;
while ((a[current1] == b[current2]) && (a[current1] != '\0') && (b[current2] != '\0'))
{
current1++;
if(current2+1 == len2)
return result;
current2++;
}
current1 = result;
}
else
{
current2 = 0;
found = false;
current1++;
}
}
return -3;
}
问题是在第二个函数(子字符串)中以某种方式出现,导致当我尝试在“这里是您的单词”行中搜索“单词”时,功能会正常工作,但是当我尝试在一行中搜索“单词”时“这是您的wwwwword”,函数返回-3(表明是否有问题)。
解决方法
对于初学者来说,有一个标准的C字符串函数strstr
,它可以确定一个字符串是否包含在另一个字符串中。
如果您需要自己编写此类函数,则函数实现看起来太复杂了。
例如if-else语句
if (a[current1] == b[current2])
{
if(!found)
{
result = current1+1;
}
else
found = true;
// ...
至少有两个原因,没有什么意义。第一个是变量result
,可以在while循环中从函数返回该变量,其中不包含找到的单词的确切索引。第二个是found
在函数中永远不能等于true。因此,if语句中的条件
if( !found )
总是评估为真。
您还忘记了在while循环之后在if语句的复合语句中重置变量current2
。
除此之外,函数参数应带有限定符const
,因为传递的字符串在函数中不会更改。函数返回类型应为size_t
。
例如,该函数可以通过以下演示程序中的以下方式查看。
#include <stdbool.h>
#include <string.h>
size_t substring( const char *s1,const char *s2 )
{
size_t n1 = strlen( s1 );
size_t n2 = strlen( s2 );
size_t i = 0;
bool found = false;
if (!( n1 < n2 ))
{
for ( size_t n = n1 - n2; !found && i <= n; i += !found )
{
size_t j = 0;
while (s2[j] != '\0' && s2[j] == s1[i + j]) ++j;
found = s2[j] == '\0';
}
}
return found ? i : -1;
}
int main( void )
{
const char *word = "word";
const char *s1 = "Here is your word";
const char *s2 = "Here is your wwwwword";
printf( "%zu\n",substring( s1,word ) );
printf( "%zu\n",substring( s2,word ) );
}
程序输出为
13
17
如果在源字符串中找不到单词,则该函数返回类型为size_t
的值,该值等于-1
。
请注意,变量字符应声明为类型int
而不是char
。否则,如果类型EOF
的行为与类型char
相同,则与unsigned char
的比较通常会产生意外结果。