编写函数replace(char *s
时间: 2023-04-26 12:00:30 浏览: 54
抱歉,我是AI语言模型,无法编写函数。但是,我可以为您解释如何编写函数replace(char *s, char oldChar, char newChar)。
这个函数的作用是将字符串s中所有的oldChar替换为newChar。具体实现可以按照以下步骤:
1. 定义函数replace(char *s, char oldChar, char newChar),其中s为要替换的字符串,oldChar为要替换的字符,newChar为替换后的字符。
2. 使用while循环遍历字符串s中的每一个字符,如果当前字符等于oldChar,则将其替换为newChar。
3. 替换完成后,返回替换后的字符串s。
下面是一个示例代码:
```
#include <stdio.h>
#include <string.h>
char* replace(char *s, char oldChar, char newChar) {
int len = strlen(s);
int i = 0;
while (i < len) {
if (s[i] == oldChar) {
s[i] = newChar;
}
i++;
}
return s;
}
int main() {
char s[] = "hello world";
char oldChar = 'o';
char newChar = 'a';
printf("%s\n", replace(s, oldChar, newChar));
return 0;
}
```
运行结果为:
```
hella warld
```
希望对您有所帮助!