实现字符串替换

题意:输入3个字符串,然后再第一个字符串中找出所有的第二个字符串,第三个字符串替换掉所有的第二个字符串,最后输出新的字符串。

本题不难的,就是使用strstr()库函数寻找到子串的位置,然后进行替换就可以了。

c语言指针操作代码:

//17/16 17:25
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>

char *my_replace(char *str, char *sub1, char *sub2, char *output)
{
	char *pOutput = NULL;
	char *pStr = NULL;
	int lenSub1 = strlen(sub1);
	int lenSub2 = strlen(sub2);

	pOutput = output;
	pStr = str;				//用于寻找子串
	while(*pStr)
	{
		pStr = strstr(pStr, sub1);   //在str中寻找sub1子串
		if(NULL != pStr)             //找到sub1子串
		{
			memcpy(pOutput, str, pStr - str);  //复制str的前一部分到output
			pOutput += pStr - str;			   //output的指针往后移动
			memcpy(pOutput, sub2, lenSub2);    //复制sub2子串到output
			pOutput += lenSub2;
			pStr += lenSub1;					//为下一次复制做准备
			str = pStr;
		}
		else
		{
			break;         //找不到sub1子串
		}
	}
	*pOutput = '\0';
	if(*str != '\0')
	{
		strcpy(pOutput, str);    //复制str剩余部分到output
	}

	return output;
}

int main()
{
	char str[50] = "";
	char sub1[10] = "";
	char sub2[10] = "";
	char output[100] = "";

	printf("str: ");
	scanf("%s", str);
	printf("sub1: ");
	scanf("%s", sub1);
	printf("sub2: ");
	scanf("%s", sub2);

	my_replace(str, sub1, sub2, output);
	printf("result: %s\n", output);

	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值