std::string 替换字串
时间: 2024-05-02 21:15:20 浏览: 13
std::string 类型提供了多种替换字串的方法,以下是其中两种常用的方法:
1. replace() 方法:该方法可以用一个新的字符串替换原始字符串中的一个子串,可以指定起始位置和长度。例如:
```
std::string str = "hello world";
str.replace(0, 5, "hi");
// 替换后 str 的值为 "hi world"
```
2. find() 和 erase() 方法:可以结合使用 find() 方法和 erase() 方法来删除原始字符串中的子串,并在该位置插入一个新的字符串,例如:
```
std::string str = "hello world";
int pos = str.find("world");
if (pos != std::string::npos) {
str.erase(pos, 5);
str.insert(pos, "there");
}
// 替换后 str 的值为 "hello there"
```
相关问题
std::string 字串转整形
可以使用`std::stoi`函数将`std::string`类型的字符串转换为整数。下面是一个示例代码:
```cpp
#include <iostream>
#include <string>
int main() {
std::string str = "12345";
int num = std::stoi(str);
std::cout << "转换后的整数为:" << num << std::endl;
return 0;
}
```
输出结果为:
```
转换后的整数为:12345
```
c++string字串
C++中的string是一个标准库类,用于处理字符串。它提供了一系列的成员函数和操作符,使得字符串的操作更加方便和高效。
以下是一些常用的string操作:
1. 创建string对象:可以使用赋值运算符或者构造函数来创建string对象,例如:
```
string str1 = "Hello"; // 使用赋值运算符
string str2("World"); // 使用构造函数
```
2. 字符串连接:可以使用"+"操作符或者成员函数append()来连接两个字符串,例如:
```
string str3 = str1 + " " + str2; // 使用"+"操作符
string str4 = str1.append(" ").append(str2); // 使用append()函数
```
3. 字符串长度:可以使用成员函数length()或者size()来获取字符串的长度,例如:
```
int len = str3.length(); // 使用length()函数
int size = str3.size(); // 使用size()函数
```
4. 字符串比较:可以使用比较操作符或者成员函数compare()来比较两个字符串,例如:
```
bool isEqual = (str1 == str2); // 使用"=="操作符
int result = str1.compare(str2); // 使用compare()函数,返回值为0表示相等
```
5. 字符串查找和替换:可以使用成员函数find()来查找子串在字符串中的位置,使用成员函数replace()来替换子串,例如:
```
size_t pos = str3.find("World"); // 查找子串的位置
str3.replace(pos, 5, "C++"); // 替换子串
```
6. 字符串切割:可以使用成员函数substr()来获取字符串的子串,例如:
```
string subStr = str3.substr(6, 5); // 获取从位置6开始的长度为5的子串
```