string删除指定字符赋值给新的string
时间: 2024-01-28 20:04:55 浏览: 23
同样可以使用STL中的erase和remove函数来删除指定字符,并将结果赋值给一个新的string对象,例如:
```cpp
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string str = "hello, world!";
char ch = 'o';
string new_str(str);
new_str.erase(remove(new_str.begin(), new_str.end(), ch), new_str.end());
cout << new_str << endl; // 输出: hell, wrld!
return 0;
}
```
其中,我们先将原始的字符串复制给一个新的string对象,然后再对新的字符串进行删除指定字符的操作。这样可以保留原始字符串不变,同时得到一个新的字符串。
相关问题
Java string删除指定字符
在 Java 中,字符串是不可变的,因此不能直接修改一个字符串中的字符。但是可以通过创建一个新的字符串,将需要保留的字符拼接起来,达到删除指定字符的效果。
例如,可以使用 `replaceAll()` 方法来删除指定字符:
```java
String str = "hello, world!";
char ch = 'o';
str = str.replaceAll(String.valueOf(ch), "");
System.out.println(str); // 输出: hell, wrld!
```
其中 `replaceAll()` 方法接受两个参数,第一个参数是需要替换的字符串或字符,第二个参数是替换后的字符串或字符。在这个示例中,我们将第一个参数设为需要删除的字符,并将第二个参数设为空字符串,即删除这个字符。
需要注意的是,这个方法会返回一个新的字符串,原来的字符串并没有被修改。因此需要将结果赋值给原来的字符串变量。
c++ string截取一段赋值给新string
在C++中,可以使用`substr()`函数来截取`string`的一段,并将其赋值给一个新的`string`变量。`substr()`函数接受两个参数,第一个参数是起始位置,第二个参数是截取的长度。下面是一个示例代码:
```cpp
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World!";
std::string newStr = str.substr(7, 5); // 从位置7开始截取5个字符
std::cout << newStr << std::endl; // 输出:World
return 0;
}
```
在上面的示例中,我们首先定义了一个`string`变量`str`,并赋值为"Hello, World!"。然后使用`substr()`函数从位置7开始截取5个字符,并将结果赋值给新的`string`变量`newStr`。最后,我们输出`newStr`的值,结果为"World"。
相关推荐
![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)