版权声明:转载请注明来源~ https://blog.csdn.net/Lth_1571138383/article/details/85267751
Github地址:φ(>ω<*)这里这里。
/*
本次任务设计并测试一个名为 char *srting_in(const char * s1, const char * s2) 的函数。
本函数要求接收两个指向字符串的指针作为参数。 如果第二个字符串包含在第一个字符串,
就返包含在第一个字符串开始的地址。就是第一个字符串有第二个字符串相同内容的位置,第一个字母的地址。
*/
#include<stdio.h>
#define n 50
char *srting_in(char * s1, char * s2);
int main(void)
{
int i = 0; // 创建这个变量是因为s2的换行符会妨碍字符匹配。
char s1[n] = {};
char s2[n] = {};
char quit = 0;
char * result = NULL;
while(quit != 'q')
{
printf("Please input the first string(The limit is 20 character):\n");
fgets(s1, n, stdin);
fflush(stdin);
printf("Please input the second string(The limit is 20 character):\n");
fgets(s2, n, stdin);
// 接下来的步骤都是处理换行符,直到 Line 38.
while(s2[i] != '\n')
{
i++;
}
if(s2[i] == '\n')
{
s2[i] = '\0';
}
fflush(stdin);
result = srting_in(s1, s2);
if(result != NULL)
{
printf("\nThe string 2 is in string 1.. The address is %p. \n", result);
}
else
{
printf("\nThe sring 2 isn't in string 1.\n");
}
printf("Do you want to quit or continue(Enter 'q' to quit)? Choies:\n");
quit = getchar();
fflush(stdin);
}
printf("Bye ~\n");
getchar();
return 0;
}
char *srting_in(char * s1, char * s2)
{
// 想法很简单,找到相同首字母的时候,用两个指针临时存放当前位置,
// 然后嵌套一个循环去继续匹配。
int i = 0; // 这个i是用于在循环中识别是否匹配成功而退出。
char * result2 = NULL;
char * temporary1 = NULL;
char * temporary2 = NULL;
while(*s1 != '\n' && *s1 != '\0')
{
if(*s1 == *s2)
{
// 存放当前s1, s2的地址。
temporary1 = s1;
temporary2 = s2;
while(*s2 != '\0')
{
if(*s1 != *s2)
{
break;
}
s1++;
s2++;
}
if(*s2 == '\0')
{
i = 1;
// 这里的意思是,经过刚刚的while循环,如果s2目前指向的位置是空字符,
// 说明s1跟s2已经匹配到s2结尾而没有任何差错,故匹配成功。接下来直接跳出大循环。
break;
}
else
{
// 如果s2不是空字符,那么说明匹配失败,则继续大循环匹配。
s2 = temporary2;
}
}
else
{
s1++;
}
}
if(i > 0)
{
result2 = temporary1;
}
else
{
result2 = NULL;
}
return result2;
}