C++ string concatenation

Started by
8 comments, last by NightCreature83 12 years, 1 month ago
Ok, this may be a dumb question, but I've been banging my head on this one for some time now. Considering the following:

std::string line = "";
int x = 7, y = 12;


What is the best way to concatenate the following and assign the result to the string variable, like so? (Obviously, this doesn't work.)

line = "(" + x + "," + y + ")";
Advertisement
I recommend append.


std::string s1 = "Hello";
std::string s2 = " World";
std::cout << s1.append(s2);


I also like StringStream a lot when appending things like integers and doubles.

P.S. http://www.cplusplus.com is your friend.

P.S.S. std::string::append will append the parameter string to the current string and return the current string so


std::string s1 = "Hello";
std::string s2 = " World";
s1.append(s2);
std::cout << s1;


would display the same thing.
That gets me past dealing with trying to concatenate strings and char values. Now, could you throw a couple of ints into the mix?
Either use a stringstream or you can use boost::lexical_cast to easily convert the ints to strings and then concatenate with +
It's all about the stringstream, baby:

#include <sstream>

int main()
{
std::ostringstream builder;
builder << "Foo: " << (40 + 2) << " and such!";

std::cout << builder.str() << std::endl;
}



Note that the syntax for cout and stringstream looks remarkably similar... this is by design. In fact, you can (if you are careful) use C++ streams to swap between writing to screen, string buffers, or even files - even on the fly at runtime.

Wielder of the Sacred Wands
[Work - ArenaNet] [Epoch Language] [Scribblings]


That gets me past dealing with trying to concatenate strings and char values. Now, could you throw a couple of ints into the mix?


You use std::stringstream.

std::stringstream stream;
stream << number;
return stream.str();


'number' could be a float or an int.

I usually wrap that in a function, 'IntToString(int)' (though you could even make the function templated).

For your situation, I go like this:

std::string line = "(%1,%2)";
int x = 7, y = 12;

line = String::Replace(line, "%1", IntToString(x));
line = String::Replace(line, "%2", IntToString(y));


Where 'Replace' is a function I created (I like to have it in a 'String' namespace, but that's up to you).
The function looks like this:
//Replaces the _first_ occurance of 'toReplace' with 'replacement' in 'str'.
std::string Replace(const std::string &str, const std::string &toReplace, const std::string &replacement)
{
//Find the first occurance of 'toReplace'.
size_t pos = str.find(toReplace);
if(pos == std::string::npos)
return str;

//Create the new string as a copy of the old.
std::string newStr = str;

//Replace 'toReplace' in the new string with 'replacement'.
newStr.replace(pos, toReplace.size(), replacement);

return newStr;
}


[Edit:] I probably only do it this way, because I don't have experience with streams. You should do it ApochPiQ's way, since it's a standardized way, instead of trying to butcher the standardized way into some C-style way.
stringstreams or boost::format are the best ways to go, boost::format being the much more flexible option

In time the project grows, the ignorance of its devs it shows, with many a convoluted function, it plunges into deep compunction, the price of failure is high, Washu's mirth is nigh.

Looks like stringstream is the way to go for me here.

I see a lot of people using boost libraries. I'm working on a cross-platform application. Should I consider using boost?
Boost is cross-platform. Boost is a set of very good, very high-quality libraries. Think of it as an optional non-official extension to the standard library guided by the people who designed the standard library.

The first place you should look if you need something is the standard library, the second place is boost, then the third place is other 3rd party libraries on the internet.
The C-way of doing this would be snsprintf or vsnsprintf as these allow you to controll the size of the buffer that is being written into. StringStream is the C++ way of fixing it but you might encounter sprintf and it's ilk in older codebases so it is good to be aware of these functions.

Worked on titles: CMR:DiRT2, DiRT 3, DiRT: Showdown, GRID 2, theHunter, theHunter: Primal, Mad Max, Watch Dogs: Legion

This topic is closed to new replies.

Advertisement