编写一个程序,当在一个字符串中出现子串时就删除它。 【输入形式】 用户在第一行输入一个字符串,用户在第二行输入一个子串。 【输出形式】 程序在下一行输出删除其中所有子串后的字符串。如果字符串不包含子串则输出原字符串本身。
时间: 2024-06-20 07:03:21 浏览: 23
你可以使用以下的步骤编写这个程序:
1. 读取用户输入的字符串和子串。
2. 使用字符串的find函数查找子串在字符串中的位置,如果找到了就删除。
3. 重复第2步直到找不到为止。
4. 输出删除子串后的字符串。
这里给出一个Python语言的实现示例:
```
# 读取用户输入的字符串和子串
s = input().strip()
sub = input().strip()
# 不断查找并删除子串,直到找不到为止
while True:
pos = s.find(sub)
if pos == -1:
break
s = s[:pos] + s[pos+len(sub):]
# 输出删除子串后的字符串
print(s)
```
相关问题
编写一个程序,当在一个字符串中出现指定子串时就删除它。
好的,我可以为您提供一个 Python 代码示例,用于删除字符串中的指定子串:
```python
def remove_substring(string, substring):
"""删除字符串中的指定子串"""
# 判断字符串是否包含子串
if substring not in string:
return string
# 使用 replace() 方法删除子串
new_string = string.replace(substring, "")
return new_string
```
使用示例:
```python
string = "Hello, World!"
substring = "l"
new_string = remove_substring(string, substring)
print(new_string) # 输出 "Heo, Word!"
```
这个程序会删除字符串中的所有指定子串,如果您只需要删除第一个出现的子串,可以使用 `replace()` 方法的第三个参数来指定替换次数。
编写一个程序,当在一个字符串中出现子串时就删除它。 【输入形式】 用户在第一行输入一个字符串,用户在第二行输入一个子串。 【输出形式】 程序在下一行输出删除其中所有子串后的字符串。如果字符串不包含子串则输出原字符串本身。用C语言实现
可以使用C语言的字符串函数来实现删除一个字符串中的子串,具体步骤如下:
1. 使用`fgets()`函数从标准输入中读取用户输入的字符串和子串;
2. 使用`strstr()`函数在字符串中查找子串,如果找到了就使用`memmove()`函数将子串后面的字符往前移动,覆盖掉子串,直到字符串中不再包含子串;
3. 输出删除子串后的字符串。
下面是一个示例代码:
```
#include <stdio.h>
#include <string.h>
int main() {
char str[100], sub[100];
fgets(str, 100, stdin);
fgets(sub, 100, stdin);
sub[strcspn(sub, "\n")] = '\0'; // 去掉fgets读入的换行符
int len = strlen(sub);
char *pos;
while ((pos = strstr(str, sub)) != NULL) {
memmove(pos, pos + len, strlen(pos + len) + 1);
}
printf("%s", str);
return 0;
}
```
相关推荐
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.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)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)