string vector to string c++
Certainly! Here's an example of converting a std::vector
of std::string
into a single std::string
in C++:
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
int main() {
std::vector<std::string> strVec = {"Hello", " ", "world", "!"};
std::ostringstream oss;
for (const std::string& str : strVec) {
oss << str;
}
std::string result = oss.str();
std::cout << "Concatenated String: " << result << std::endl;
return 0;
}
Explanation:
#include
directives: Include necessary headers for using strings, vectors, input/output streams, and stringstreams.main()
: The main function where the program execution begins.std::vector<std::string> strVec = {"Hello", " ", "world", "!"};
: Declaration and initialization of a vectorstrVec
containing strings.std::ostringstream oss;
: Creation of an output string streamoss
to build the concatenated string.for (const std::string& str : strVec) { oss << str; }
: Iterating through each string in the vectorstrVec
and appending it to theoss
stringstream.std::string result = oss.str();
: Retrieving the concatenated string from the stringstreamoss
usingstr()
function and storing it in theresult
string.std::cout << "Concatenated String: " << result << std::endl;
: Outputting the concatenated string to the console.return 0;
: Returning 0 to indicate successful execution of the program.
This code snippet creates a vector of strings, concatenates them into a single string using an output stringstream, and then outputs the resulting concatenated string.