第1关:删除字符串中的指定字符
时间: 2023-06-20 18:05:42 浏览: 101
题目描述:给定一个字符串和一个字符,将字符串中所有的指定字符删除。
示例:
输入:str = "hello world", char = 'l'
输出:heo word
输入:str = "leetcode", char = 'e'
输出:lctod
解题思路:遍历字符串中的每个字符,如果当前字符不等于指定字符,则将该字符加入到结果字符串中。
参考代码:
```python
def delete_char(str, char):
res = ""
for c in str:
if c != char:
res += c
return res
```
测试一下:
```python
print(delete_char("hello world", 'l')) # heo word
print(delete_char("leetcode", 'e')) # lctod
```
相关问题
c++ 删除字符串中指定字符
你可以使用C++中的字符串操作函数来删除字符串中的指定字符。以下是一种常见的方法:
```cpp
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World!";
char target = 'o';
std::string result;
for (char c : str) {
if (c != target) {
result += c;
}
}
std::cout << "Original string: " << str << std::endl;
std::cout << "Modified string: " << result << std::endl;
return 0;
}
```
在上述示例中,我们通过遍历原始字符串中的每个字符,并将不等于目标字符的字符添加到结果字符串中,从而删除了指定字符。最后,我们打印出原始字符串和修改后的字符串。
运行上述代码将输出:
```
Original string: Hello, World!
Modified string: Hell, Wrld!
```
请注意,上述代码只会删除第一个出现的目标字符。如果要删除字符串中所有的目标字符,可以使用其他方法,如使用`std::remove_if`函数结合lambda表达式。
字符串中只删除一个指定字符串
可以通过字符串的replace方法和count方法来实现。先使用count方法判断指定字符串在原字符串中出现的次数,如果出现次数大于等于2,则使用replace方法删除第一个出现的指定字符串。如果只出现了一次,则直接使用replace方法删除该指定字符串即可。
下面是Python代码示例:
```python
def delete_one_string(s, target):
count = s.count(target)
if count >= 2:
return s.replace(target, '', 1)
elif count == 1:
return s.replace(target, '')
else:
return s
```
其中,s为原字符串,target为要删除的指定字符串。如果指定字符串在原字符串中出现了多次,使用replace方法并设置count参数为1可以删除第一个出现的指定字符串。如果指定字符串只出现了一次,则直接使用replace方法删除即可。如果指定字符串没有出现,则直接返回原字符串。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)