I declared char * array char *excluded_string[50] = { 0 };
Later each element of ex_str array gets one word. Now I want to convert it into string so that I can have all words seperated by space.
To convert it into a single string:
char *excluded_string[50] = { 0 };
// excluded_string filled in the meantime
std::ostringstream buffer; // add #include <sstream> at the top of
// the file for this
for(int i = 0; i < 50; ++i)
buffer << excluded_string[i] << " ";
std::string result = buffer.str();
Edit: A few notes:
if possible, do not concatenate strings directly: that will create and destroy a lot of objects and perform lots of unnecessary allocations.
if your code has stringent efficiency requirements, consider allocating/reserving the result beforehand to ensure a single allocation instead of repeated allocations.
if you concatenate strings, consider using operator += instead of + and =.
Edit 2: (answering comments)
What if + and = instead of +=?
Here's the resolution of the two alternatives for concatenating strings (s += s1 + s2 vs s += s1; s += s2):
code:
std::string ss;
for (int i=0; i<50; i++)
ss += std::string(excluded_string[i]) + " ";
Equivalent code (in terms of objects constructed and allocations):
std::string ss;
for (int i=0; i<50; i++)
{
// ss += std::string(excluded_string[i]) + " ";
std::string temp1(excluded_string[i]); // "std::string(excluded_string[i])"
std::string temp2 = temp1 + " "; // call std::string operator+(std::string, char*)
ss += temp2; // call std::string::operator +=(std::string)
}
- temp1 is created once per iteration;
- temp2 is created for the concatenation operator
- the second temporary is appended to ss.
Both temporaries create a copy of the data (allocate buffer, copy data, deallocate buffer).
code:
std::string ss;
for (int i=0; i<50; i++)
{
ss += excluded_string[i]; // call std::string::operator +=(char*)
ss += " "; // same as above
}
std::string::operator += is called twice; It allocates space (if necessary), copies current contents of the string to newly allocated space, then copies new data at the end of the allocated buffer.
single pre-allocated space:
allocating/reserving the result beforehand to ensure a single allocation
std::size_t total_length = 0;
for(int i = 0; i < 50; ++i)
total_length += std::strlen(excluded_strings[i]); // assumes argument is not null
std::string ss;
ss.reserve(total_length + 51); // reserve space for the strings and spaces between
for (int i=0; i<50; i++)
{
ss += excluded_string[i]; // calls std::string::operator +=
ss += " "; // same as above
}
In this case, operator+= doesn't allocate space internally, just at the beginning (a single operation). This is still a bit slow, because you iterate over the strings twice (0->49) and over each string twice (once to compute length, once to copy it to ss).
If your excluded_string were a std::vector instead, it would be more efficient because computing the strings lengths would not iterate each string, just the vector).