std::string 字符串删除
时间: 2023-11-05 08:04:49 浏览: 150
在C++中,可以使用std::erase和std::remove函数来删除std::string字符串中的指定字符。首先,使用std::remove函数将要删除的字符移到字符串的末尾,然后使用std::erase函数擦除末尾的字符。以下是一个示例:
std::string str = "string:-name:-sponge-";
str.erase(std::remove(str.begin(), str.end(), '-'), str.end());
在上面的示例中,字符串str中的字符'-'被删除,最终结果为"string:name:sponge"。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
相关问题
std::string 实现字符串 replace
可以使用 C++ 的标准库中的 `std::string` 类来实现字符串替换。`std::string` 类提供了 `replace` 方法,可以用来替换指定位置的字符串。
示例代码如下:
```c++
#include <iostream>
#include <string>
int main() {
std::string str = "hello world";
std::cout << "原始字符串: " << str << std::endl;
// 将 "world" 替换为 "C++"
str.replace(str.find("world"), 5, "C++");
std::cout << "替换后的字符串: " << str << std::endl;
return 0;
}
```
输出结果为:
```
原始字符串: hello world
替换后的字符串: hello C++
```
在代码中,我们使用 `find` 方法找到字符串中 "world" 的位置,然后使用 `replace` 方法将其替换为 "C++"。其中,第一个参数指定要替换的字符串的起始位置,第二个参数指定要替换的字符串的长度,第三个参数指定用来替换的字符串。
std::string 与字符串比较函数
在 C++ 中,可以使用 `std::string` 类型来表示字符串。`std::string` 类型有一个成员函数 `compare()` 用于比较两个字符串。其语法如下:
```c++
int compare(const std::string& str) const;
```
该函数将当前字符串与参数 `str` 进行比较,返回值为整数,含义如下:
- 如果当前字符串小于 `str`,返回负数;
- 如果当前字符串等于 `str`,返回零;
- 如果当前字符串大于 `str`,返回正数。
使用示例:
```c++
#include <iostream>
#include <string>
int main() {
std::string str1 = "hello";
std::string str2 = "world";
int result = str1.compare(str2);
if (result < 0) {
std::cout << "str1 is less than str2" << std::endl;
} else if (result == 0) {
std::cout << "str1 is equal to str2" << std::endl;
} else {
std::cout << "str1 is greater than str2" << std::endl;
}
return 0;
}
```
输出结果为:
```
str1 is less than str2
```
阅读全文
相关推荐














