编写算法删除字符串s中值等于ch(变量名)的所有字符。
时间: 2023-06-03 18:02:41 浏览: 78
好的,这个问题是可以回答的。以下是算法实现的示例代码:
```
def removeChar(s, ch):
new_s = ""
for c in s:
if c != ch:
new_s += c
return new_s
s = "Hello, world!"
ch = "o"
new_s = removeChar(s, ch)
print(new_s) # 输出 "Hell, wrld!"
```
这个算法的实现比较简单,就是遍历字符串中的每一个字符,如果这个字符不等于要删除的字符,就将它添加到新的字符串中,最后返回新的字符串即可。
相关问题
编写算法删除字符串s中值等于ch(变量名)的第一个字符
您好,可以使用以下算法删除字符串s中值等于ch的第一个字符:
1. 遍历字符串s,找到第一个值等于ch的字符所在的位置pos;
2. 将pos位置后面的字符都往前移动一位,覆盖pos位置上的字符;
3. 最后删除字符串s的最后一个字符。
以下是代码示例:
```
void removeChar(char *s, char ch) {
int pos = -1;
for (int i = 0; i < strlen(s); i++) {
if (s[i] == ch) {
pos = i;
break;
}
}
if (pos != -1) {
for (int i = pos; i < strlen(s) - 1; i++) {
s[i] = s[i + 1];
}
s[strlen(s) - 1] = '\0';
}
}
```
希望能对您有所帮助,如果有其他问题可以继续提问哦。
编写算法删除字符串s中值等于ch(变量名)的所有字符,用c语言实现
好的,我了解了您的要求。下面是C语言实现删除字符串s中值等于ch的所有字符的代码:
```c
#include <stdio.h>
#include <string.h>
void removeChar(char *s, char ch) {
int len = strlen(s);
int j = 0;
for (int i = 0; i < len; i++) {
if (s[i] != ch) {
s[j] = s[i];
j++;
}
}
s[j] = '\0';
}
int main() {
char s[100];
char ch;
printf("请输入字符串: ");
fgets(s, 100, stdin);
printf("请输入要删除的字符: ");
scanf("%c", &ch);
removeChar(s, ch);
printf("删除后的字符串为: %s\n", s);
}
```
您可以将要删除的字符串存储在字符数组s中,将要删除的字符存储在char类型的变量ch中。函数removeChar()将遍历字符串s中的每个字符,如果字符不等于ch,则将其存储在原始字符串的位置。最后用'\0'结束字符串。