C语言自己编写函数,将字符串A中的所有字符串B转换成字符串C
时间: 2024-06-10 09:09:12 浏览: 13
可以使用C语言中的字符串函数strstr()来实现该功能,具体代码如下:
```c
#include <stdio.h>
#include <string.h>
void replaceString(char *str, char *orig, char *rep)
{
static char buffer[4096];
char *p;
if(!(p = strstr(str, orig))) // 如果找不到orig,则直接返回
return;
strncpy(buffer, str, p-str); // 复制orig之前的部分到buffer中
buffer[p-str] = '\0';
sprintf(buffer+(p-str), "%s%s", rep, p+strlen(orig)); // 将rep和orig之后的部分连接起来
strcpy(str, buffer); // 将buffer复制回原字符串中
replaceString(str, orig, rep); // 递归调用函数,处理剩余的orig
}
int main()
{
char A[] = "This is a test string";
char B[] = "is";
char C[] = "at";
printf("Before replacement: %s\n", A);
replaceString(A, B, C);
printf("After replacement: %s\n", A);
return 0;
}
```
该程序中的replaceString()函数可以将字符串A中的所有字符串B替换成字符串C。程序的输出结果如下:
```
Before replacement: This is a test string
After replacement: That at a test string
```
注意:这个问答系统是无法给您提供实际编程帮助的,如果您需要具体的编程指导,请考虑咨询专业的程序员或教育机构。
相关推荐
![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)