c++string装多个字符串
时间: 2023-08-20 21:09:58 浏览: 43
在 C++ 中,你可以使用 `std::string` 类来装载多个字符串。有几种方法可以实现这个目的:
1. 使用 `+` 运算符来连接字符串:
```cpp
std::string result = "Hello";
result += " World";
result += "!";
```
2. 使用 `append()` 函数来连接字符串:
```cpp
std::string result = "Hello";
result.append(" World");
result.append("!");
```
3. 使用 `std::stringstream` 类来拼接字符串:
```cpp
#include <sstream>
std::stringstream ss;
ss << "Hello";
ss << " World";
ss << "!";
std::string result = ss.str();
```
4. 使用 `std::string` 的构造函数来连接字符串:
```cpp
std::string result = std::string("Hello") + " World" + "!";
```
无论你选择哪种方法,最终结果都会是 `result` 字符串包含了多个字符串的连接。
相关问题
C++ string 替换指定字符串
你可以使用C++中的string类提供的replace函数来替换指定字符串。replace函数的参数是替换起始位置、替换长度和替换内容。以下是一个简单的示例代码:
```c++
#include <string>
#include <iostream>
using namespace std;
int main() {
string s = "Hello world!";
string old_str = "world";
string new_str = "C++";
size_t pos = s.find(old_str);
if(pos != string::npos) {
s.replace(pos, old_str.length(), new_str);
}
cout << s << endl; // 输出:Hello C++!
return 0;
}
```
在这个示例代码中,我们首先使用find函数找到要替换的字符串的起始位置。如果找到了要替换的字符串,就使用replace函数进行替换。最后输出替换后的字符串。需要注意的是,如果要替换的字符串在原字符串中出现多次,上述代码只会替换第一次出现的字符串。
string替换多个子字符串代码
以下是一个使用 C++ 的示例代码,用于将字符串中的多个子字符串替换为另一个字符串:
```cpp
#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;
int main() {
string str = "Hello, world! Today is a beautiful day!";
unordered_map<string, string> replace_map = {{"world", "everyone"}, {"beautiful", "wonderful"}};
for (auto& [search_str, replace_str] : replace_map) {
size_t pos = str.find(search_str);
while (pos != string::npos) {
str.replace(pos, search_str.length(), replace_str);
pos = str.find(search_str, pos + replace_str.length());
}
}
cout << str << endl;
return 0;
}
```
在这个示例代码中,我们首先定义了一个字符串 `str`,其中包含多个子字符串需要替换。然后,我们定义了一个无序映射 `replace_map`,其中每个键表示需要替换的子字符串,对应的值表示替换为的字符串。
接下来,我们使用 `find` 函数查找每个需要替换的子字符串在 `str` 中的位置。如果找到了,我们使用 `replace` 函数将其替换为对应的值。然后,我们更新查找的起始位置,以继续查找下一个需要替换的子字符串,直到找不到为止。
最后,我们输出替换后的字符串 `str`。