How to convert string array elements into a single string?

I have a string array with different letters in each space. How can I convert it into a single string so that I can compare if it is the same to a separate string I have?
Say the string array is as follows:

str[1] = "_";
str[2] = "a";
str[3] = "_";

and so on. I would like to make that array turn a separate string into, say:

str2 = "_a_";
When you say you have a string array, do you mean you have an array of string objects, like this:
string str[10];
or do you mean an array of char, like this:
char str[10];?
I have an array like this:
string srt[10];
I would like to put all of those elements into this:
string str2;
Last edited on
std::string str2( str );

provided that the character array has terminated zero symbol.
Last edited on
That code didn't work. I think it is because it isn't a character array, it is a string array (array of string objects) :/
Then use standard algorithm std::accumulate

1
2
3
4
5
std::string str2;

std::accumulate( std::begin( str ), sttd::end( str ), &str2,
                          [] ( std::string *p, const std::string &s ) 
                         { return ( &p->append( s ) ); } ); 
Last edited on
+1 for use of lambda.
I have not understood why using of the lambda did have such impression?
Last edited on
I tried putting that in, and it did not compile so I did some quick research. I found:

1
2
3
4
5
6
7
template <class InputIterator, class T>
   T accumulate ( InputIterator first, InputIterator last, T init )
{
  while ( first!=last )
    init = init + *first++;  // or: init=binary_op(init,*first++) for the binary_op version
  return init;
}


using this it complies okay, but when I use the call:
accumulate(str,str,str2)
Nothing happens.

Sorry if I don't seem to get it, I've only been programming a couple months.
There's never any point in over-complicating things:
1
2
string str2;
for (auto& s : str)str2+=s;


I tried putting that in, and it did not compile

That code (and the one above) uses C++11 features, so you need a recent compiler and you might need to compile with -std=c++0x depending on which one you use.
Last edited on
I use Dev C++; I know it is antiquated and 'bad' , but that is the compiler we have to use for class. Is there any way I can get it to work with it?

Also, I received a compile error with
1
2
 string str2;
for (auto& s : str)str2+=s;


" expected `;' before "auto" "
and
" expected `)' before ';' token "

Also due to the old compiler I guess >_<
Last edited on
In that case don't bother and do the following:
for (int i=0;i<arraySize;i++)str2+=str[i];
If the compiler supports lambda expressions then use the example I showed or write a functional object imstead of the lambda expression.
Thank you so much!!! You have just made me quite happy. I couldn't figure this out for the life of me, and for (int i=0;i<arraySize;i++)str2+=str[i]; worked! :D
Topic archived. No new replies allowed.