编写一个函数实现从源字符串中查找目标字符串,并进行替换。如输入源字符串“We love math!" ,查找目标字符串“math",并将其替换为字符串“CProgram”,在主函数中输出替换后的字符串“Welove C Program ! (1)从键盘输入源字符串; (2)从键盘输入目标字符串和替换的字符串; (3)调用函数实现查找源字符串中的目标字符串,并进行替换; . (4)输出完成查找和替换后的字符串。
时间: 2023-08-21 15:04:17 浏览: 47
好的,以下是实现该功能的函数代码:
```c
#include <stdio.h>
#include <string.h>
void replaceString(char source[], char target[], char replace[])
{
int i, j, k;
int sourceLen = strlen(source);
int targetLen = strlen(target);
int replaceLen = strlen(replace);
char temp[100];
for (i = 0; i <= sourceLen - targetLen; i++)
{
for (j = i; j < i + targetLen; j++)
{
temp[j - i] = source[j];
}
temp[targetLen] = '\0';
if (strcmp(temp, target) == 0)
{
for (k = i; k < i + replaceLen; k++)
{
source[k] = replace[k - i];
}
i += replaceLen - 1;
}
}
}
int main()
{
char source[100];
char target[20];
char replace[20];
printf("请输入源字符串:");
gets(source);
printf("请输入目标字符串:");
gets(target);
printf("请输入替换字符串:");
gets(replace);
replaceString(source, target, replace);
printf("替换后的字符串为:\n%s", source);
return 0;
}
```
在上述代码中,我们定义了一个 `replaceString` 函数来实现从源字符串中查找目标字符串,并进行替换的功能。该函数接受三个参数,分别为源字符串、目标字符串和替换字符串。具体实现采用了两层循环,第一层循环用于遍历源字符串,第二层循环用于比较源字符串中的子串是否与目标字符串相同。如果相同,则将源字符串中的目标字符串替换为替换字符串。
在主函数中,我们首先从键盘读入源字符串、目标字符串和替换字符串,然后调用 `replaceString` 函数实现查找和替换操作。最后输出替换后的字符串。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)