std::vector<std::string> 不使用iostream 转换成“,”间隔的长字符串
时间: 2023-04-03 16:01:47 浏览: 102
可以使用字符串流stringstream来实现,具体代码如下:
std::vector<std::string> vec = {"hello", "world", "CSDN"};
std::stringstream ss;
for (const auto& str : vec) {
ss << str << ",";
}
std::string result = ss.str();
result.pop_back(); // 去掉最后一个逗号
std::cout << result << std::endl; // 输出结果:hello,world,CSDN
相关问题
std::vector<std::string> 转换成“,”间隔的长字符串
可以使用 std::stringstream 和 for 循环将 vector 中的每个字符串拼接成一个长字符串,中间用逗号隔开。具体代码如下:
```
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
int main() {
std::vector<std::string> vec = {"hello", "world", "how", "are", "you"};
std::stringstream ss;
for (int i = ; i < vec.size(); i++) {
ss << vec[i];
if (i != vec.size() - 1) {
ss << ",";
}
}
std::string result = ss.str();
std::cout << result << std::endl;
return ;
}
```
输出结果为:
```
hello,world,how,are,you
```
std::vector<std::string> 转字符
如果你是要将`std::vector<std::string>`转换为一个单一的字符串,可以使用`std::stringstream`类进行操作。以下是一个示例代码:
```cpp
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
int main() {
std::vector<std::string> v = {"hello", "world", "!"};
std::stringstream ss;
for (const auto& str : v) {
ss << str << " ";
}
std::string result = ss.str();
std::cout << result << std::endl;
return 0;
}
```
这个程序将会输出 `hello world !`。在这个例子中,我们使用了一个 `std::stringstream` 对象来将所有的字符串连接起来,并且在每个字符串之间加上了空格。