strstr函数模拟实现

strstr


  1. 函数标准格式
char *strstr( const char *string, const char *strCharSet );
  1. 函数功能
  • Find a substring. 翻译为 寻找子串。子串就是一个字符串中的一部分。如字符串abcdefg,那么abc是它的子串,cde也是它的子串。只要是和字符串的一部分相同就算是子串
  • 返回值是子串在字符串中首次出现的位置(地址)
  • 子串是空串时,返回的是主字符串
  • 在主字符串中没有发现子串时,返回NULL
  1. 函数实现
char *my_strstr(const char *str1, const char *str2)
{
	assert(str1 && str2);                   //检查合法性
	const char *str = (const char*)str1;    //保护参数
	const char *substr = (const char*)str2;
	char *pstr = NULL;

	if (*substr == '\0')        //防止子串是空串
		return str1;            //子串是空串时,返回字符串         

	while (*str)         //相当于while(*src != '\0')
	{
		pstr = str;
		substr = str2;      //每次循环时,都会回到子串的首地址
		while (*pstr && *substr && (*pstr == *substr))   //若是假子串,在往后循环时就会被检测出来。
		{
			pstr++;
			substr++;
		}
		if (*substr == '\0')
			return str;
		str++;
	}
}
  1. 例子
char *my_strstr(const char *str1, const char *str2)
{
	assert(str1 && str2);                   //检查合法性
	const char *str = (const char*)str1;    //保护参数
	const char *substr = (const char*)str2;
	char *pstr = NULL;

	if (*substr == '\0')        //防止子串是空串
		return str1;            //子串是空串时,返回字符串         

	while (*str)         //相当于while(*src != '\0')
	{
		pstr = str;
		substr = str2;      //每次循环时,都会回到子串的首地址
		while (*pstr && *substr && (*pstr == *substr))   //若是假子串,在往后循环时就会被检测出来。
		{
			pstr++;
			substr++;
		}
		if (*substr == '\0')
			return str;
		str++;
	}
}

int main()
{
	char str[] = "This is a simple string";
	char *pch;
	pch = my_strstr(str, "simple");
	strncpy(pch, "sample", 6);     //规定复制字符个数的字符串复制函数
	puts(str);
	return 0;
}
  • 程序结果
    在这里插入图片描述
  • 可以看到 strstr 函数在字符串中找到了子串simple的位置,并把子串第一次出现的地址返回。strncpy 函数把sample复制进主字符串,地址为子串的地址,由于sample和simple的字符个数相同,所以完全替换simple。
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值