当前位置:网站首页>模拟实现strstr
模拟实现strstr
2022-07-20 09:42:00 【VisionaryHS】
strstr函数的参数是两个char*类型的指针,返回值是char*类型的指针,其作用是寻找字符串中的子串是否存在,若存在则 返回str1中子串(来源于str2)的起始地址,若不存在,则返回空指针
下面来实现mystrstr
- 首先将参数设计的和原函数strstr一样
- 进入函数后先断言p1和p2是否为空指针
- 保持p2不动,若p1和p2所指向的内容不同,则p1++
- 当p1内容和p2相同的时候,用char*start记录下p1的地址
- 再定义flag,用于判断是否进入while循环,定义count用于记录p1进入第二个循环后相较于start位置的偏移量。
- 正常情况下,*p1==*p2,p1和p2自己++,count也++
- 若遇到所需寻找的子串结束时,也就是*p2==‘\0’时flag=0.结束循环,并返回start的地址
- 可能出现如下情况就会进入else语句。原因是有重复的字符存在。这时候start就要重新记录起始位置
char* mystrstr(const char* p1, const char* p2)
{
assert(p1 && p2);
while (*p1 != *p2)
{
p1++;
}
char* start = p1;
int count = 0;
int flag = 1;
while (flag)
{
if (*p1 == *p2 )
{
p1++;
p2++;
count++;
}
else if (*p2 == '\0')
{
flag=0;
}
else
{
p2--;
start++;
}
}
return start;
}char* mystrstr(const char* p1, const char* p2)
{
assert(p1 && p2);
while (*p1 != *p2)
{
p1++;
}
char* start = p1;
int count = 0;
int flag = 1;
while (flag)
{
if (*p1 == *p2 )
{
p1++;
p2++;
count++;
}
else if (*p2 == '\0')
{
flag=0;
}
else
{
p2--;
start++;
}
}
运行结果
边栏推荐
猜你喜欢
What is stack?
Qt|qlabel displays multiple lines of text. If there is too much text, ellipsis will be displayed
Redis-SortSet类型
C# DataGridView数据导出Excel文件
[code hoof set novice village question 600] how to change the binary value at the even position of all binaries of a decimal integer to 0
SPSS kmeans clustering practice
APK打包流程
Cloud foundry development 4 CF command
strcat() - 连接字符串
煤炭行业供应链集采系统:数字化推进煤炭产业转型升级
随机推荐
十年架构五年生活-03作为技术组长的困扰
我的创作纪念日(3周年)
strcat() - 连接字符串
在 Business Application Studio 里使用 SAP UI5 应用消费 OData 的 Create 和 Delete 操作
【u-boot】u-boot运行主线分析【03】—board_init_r
项目启动端口被占用的解决办法
利用神器Typora+PicGo,实现有道云不用会员就可在Markdown自动上传图片
Stm32+dht11 reading temperature and humidity data display
Source code of short video live broadcast system
【C语言】程序的编译(预处理)
Cloud foundry development 4 CF command
开源轻量级工作流WorkflowCore介绍
arthas 案例: 动态更新应用Logger Level
C语言文件操作函数讲解
Guys, do PostgreSQL CDC and PostgreSQL have to configure logical replication? Currently deployed
学习记录[email protected]之moveExecutionsToSingleActivityId并行网关或者包容网关回退
APK打包流程
分类中ICO对象
幼儿园核酸预约登记小程序实战开发(下篇)
发电机组工作安排问题代码