编写函数,功能为将字符串s中的字符c1用字符c2替换,并加以调用
时间: 2023-06-12 14:04:53 浏览: 76
以下是将字符串中的字符c1用字符c2替换的Python函数:
```python
def replace_char(s, c1, c2):
return s.replace(c1, c2)
```
其中,s为待替换的字符串,c1为要替换的字符,c2为替换后的字符。
例如,将字符串"hello world"中的字母"o"替换为"i",可以调用该函数如下:
```python
new_str = replace_char("hello world", "o", "i")
print(new_str) # 输出 "helli wirld"
```
你可以根据自己的需求使用该函数。
相关问题
用c语言编写函数,功能为将字符符串中的字符c1用字符c2替换,并加以调用
以下是用 C 语言编写的函数,实现将字符串中的字符 c1 替换为字符 c2 的功能:
```c
#include <stdio.h>
#include <string.h>
void replace_char(char* str, char c1, char c2) {
int len = strlen(str);
for (int i = 0; i < len; i++) {
if (str[i] == c1) {
str[i] = c2;
}
}
}
int main() {
char str[100];
char c1, c2;
printf("请输入字符串:");
scanf("%s", str);
printf("请输入要替换的字符:");
scanf(" %c", &c1);
printf("请输入替换成的字符:");
scanf(" %c", &c2);
replace_char(str, c1, c2);
printf("替换后的字符串为:%s\n", str);
return 0;
}
```
在 main 函数中,首先输入原始字符串、要替换的字符 c1 和替换成的字符 c2。然后调用 replace_char 函数,将字符串中的 c1 替换成 c2。最后输出替换后的字符串。
#编写一个名为 swip_swap的函数 #该函数读取字符串源和字符 c1和 c2,并返回字符串源,其中所有出现的c1和c2都被交换
下面是 Python 3 的代码实现:
```python
def swip_swap(source, c1, c2):
"""
交换字符串中所有出现的c1和c2
"""
result = ""
for char in source:
if char == c1:
result += c2
elif char == c2:
result += c1
else:
result += char
return result
```
函数 `swip_swap` 接收三个参数:字符串 `source`、字符 `c1` 和字符 `c2`。函数遍历字符串 `source` 中的所有字符,如果字符是 `c1`,则将其替换为 `c2`,如果字符是 `c2`,则将其替换为 `c1`,否则保留原字符。最后返回替换后的字符串。
例如,调用 `swip_swap("hello world", "l", "o")`,将返回 `"heooo worod"`。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)