输入2个字符串S1和S2,要求删除字符串S1中出现的所有子串S2,即结果字符串中不能包含S2。 输入格式: 输入在2行中分别给出不超过80个字符长度的、以回车结束的2个非空字符串,对应S1和S2。 输出格式: 在一行中输出删除字符串S1中出现的所有子串S2后的结果字符串。 用C语言怎么写代码
时间: 2023-03-11 14:42:34 浏览: 89
答:用C语言实现此题可以采用字符串替换函数strrep,具体实现方法如下: char* strrep(char* str, char* s1, char* s2)
{
char* result;
char* str_cp = strdup(str);
char* pos = strstr(str_cp, s1);
int len = strlen(s2);
int i = 0;
while(pos != NULL)
{
for(i = 0; i < len; i++)
*(pos + i) = s2[i];
pos = strstr(str_cp, s1);
}
result = strdup(str_cp);
free(str_cp);
return result;
}
相关问题
输入2个字符串s1和s2,要求删除s1中出现的所有子串s2,即结果字符串中不能包括s2
以下是Python代码实现:
```python
def remove_substring(s1, s2):
result = ""
i = 0
while i < len(s1):
if s1[i:i+len(s2)] == s2:
i += len(s2)
else:
result += s1[i]
i += 1
return result
```
函数`remove_substring`接受两个字符串`s1`和`s2`,并返回一个新的字符串,其中`s1`中出现的所有子串`s2`都被删除了。
函数的实现是通过遍历`s1`的每个字符,如果当前字符及其之后的字符与`s2`相同,则跳过`s2`长度的字符,否则将当前字符添加到结果字符串中。
例如,如果`s1="hello world"`,`s2="l"`,则函数将返回`heo word`。
输入2个字符串S1和S2,要求删除字符串S1中出现的所有子串S2,即结果字符串中不能包含S2。
可以使用字符串替换的方法来实现删除字符串S1中所有出现的子串S2。具体步骤如下:
1. 使用字符串的 replace() 方法,将S1中所有的S2替换为空字符串 ""。
2. 返回替换后的S1字符串。
以下是 Python 代码实现:
```python
def delete_substring(s1, s2):
return s1.replace(s2, "")
```
示例:
```python
s1 = "hello world, world is beautiful"
s2 = "world"
result = delete_substring(s1, s2)
print(result) # 输出:hello , is beautiful
```
注意:该方法只能删除S1中出现的所有S2子串,无法处理S1中某些子串被S2包含的情况。例如,若S1="hello worl",S2="world",则该方法无法处理。
相关推荐
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![c](https://img-home.csdnimg.cn/images/20210720083646.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)