检测字符串之间的包含关系
//编写一个名为string_in()的函数,接受两个指向字符串的指针作为参
//数。如果第1个字符串中包含第2个字符串,该函数将返回第1个字符串开始
//的地址。例如,string_in("hats", "at")将返回hats中h的地址。否则,该函数返
//回空指针。在一个完整的程序中测试该函数,使用一个循环给函数提供输入
//值。
#include <stdio.h>
#include <string.h>
#define SIZE 80
void input_char(char *st,int n);
char* string_in(char *big,char *small);
int main(void)
{
char big_array[SIZE];
char small_array[SIZE];
char *ren_val=NULL;
int n=1;
while (n)
{
input_char(big_array,SIZE);
input_char(small_array,SIZE);
ren_val=string_in(big_array,small_array);
printf("print the return value :%p\n",ren_val);
puts("You can enter a char that not 0 to compain again and enter 0 to quit!");
scanf("%d",&n);
}
return 0;
}
void input_char(char *st,int n)
{
puts("Please enter a characters you want:");
char *ren_val=NULL;
while (*(ren_val=fgets(st,n,stdin))=='\n')
{
puts("The first char can't be Enter Key!");
puts("Please try again!");
continue;
}
if (ren_val != NULL)
{
int i=0;
while (st[i] != '\n'&&st[i] != '\0')
{
i++;
}
if (st[i] == '\n')
{
st[i]='\0';
}
else
{
while (getchar() != '\n')
continue;
}
}
return;
}
char* string_in(char *big,char *small)
{
char *point_1=big;
char *ren_val=NULL;
if (strlen(small)>strlen(big))
{
puts("The second characters isn't involved in the first one!");
}
else
{
int i=0;
while (i<strlen(small)&&*point_1 != '\0')//当point_1解引用后等于0,说明指针已经移动到最后,说明这两个字符串到最后也没匹配上。
{
if (*(point_1+i)==*(small+i))
{
i++;
}
else
{
i=0;
point_1++;
}
}
if (i==strlen(small))
{
puts("The second characters in the first one!");
ren_val=big;
}
else
{
puts("The second characters isn't involved in the first one!");
}
}
return ren_val;
}
重点:string_in()函数的分析:
如果字符串B包含在字符串A中,那么A中一定会有连续的strlen(B)个字符是一一对应着与B中的字符们相等。
1.利用上面这个原理,在函数中设置一个计数器i,
2.从A中的第一个字符开始匹配,如果A中的第一个字符和B中的第一个字符相等,那么计数器加一,接着比较第二个,以此类推......
3.当字符出现不相等的时候说明从第一个字符开始不可能出现B中的字符串,因此把指针向后面移动一位,并且计数器i清零。以此类推......
4.由于i的初始值是0,并且每次比对成功都会对i加1,因此当i=strlen(B)时,说明完全配对,此时也正好跳出循环。
5.但是也可能不会匹配上,这种情况时,指向A的那个指针会一直向后移动,并且移动到空字符处就能判断出匹配失败,因此为了不让序一直循环,再循环头中加入*point != '\0'这一条件。
6.由于跳出循环有两种情况,所以再在后面进行分类讨论即可。

浙公网安备 33010602011771号