C语言编程>第十九周 ① 下列给定程序中,函数fun的功能是:将str所指字符串中出现的temp1所指子串全部替换成temp2所指子字符串,所形成的新串放在result所指的数组中。

例题:下列给定程序中,函数fun的功能是:将str所指字符串中出现的temp1所指子串全部替换成temp2所指子字符串,所形成的新串放在result所指的数组中。在此处,要求temp1和temp2所指字符串的长度相同。

例如,当 str所指字符串中的内容为sdfadijfsdfifdsdf,temp1所指子串中的内容为sdf,temp2所指子串中的内容为000时,在result所指的数组中的内容应为000adijf000ifd000。
注意:不要改动main函数,不能增行或删行,也不能更改程序的结构。

代码如下:

#include<conio.h>
#include<stdio.h>
#include<string.h>
void fun(char*str,char*temp1,char*temp2,char*result)
{
    
    
	char*p,*r,*a;
	strcpy(result,str);
	while(*result)
	{
    
    
		p=result;
		r=temp1;
		while(*r)
		if(*r==*p)
		{
    
    
			r++;
			p++;
		}
		else
		{
    
    
			break;
		}
		if(*r=='\0')
		{
    
    
			a=result;
			r=temp2;
			while(*r)
			{
    
    
				*a=*r;
				a++;
				r++;
			}
			result+=strlen(temp2);
		}
		else
		{
    
    
			result++;
		}
	}
}
main()
{
    
    
	char str[200],temp1[200],temp2[200],result[200];
	printf("\nInput the test string str:");
	scanf("%s",str);
	printf("\nInput the first substring temp1:");
	scanf("%s",temp1);
	printf("\nInput the second substring temp2:");
	scanf("%s",temp2);
	if(strlen(temp1)==strlen(temp2))
	{
    
    
		fun(str,temp1,temp2,result);
		printf("\nThe combin result is:%s\n",result);
	}
	else
	{
    
    
		printf("Error:strlen(temp1)!=strlen(temp2)\n");
	}
}

输出运行窗口如下:
在这里插入图片描述

越努力越幸运!
加油,奥力给!!!

猜你喜欢

转载自blog.csdn.net/qq_45385706/article/details/112382307