How do I concatenate multiple C++ strings on one line?
#include <sstream>
#include <string>
std::stringstream ss;
ss << "Hello, world, " << myInt << niceToSeeYouString;
std::string s = ss.str();
Take a look at this Guru Of The Week article from Herb Sutter: The String Formatters of Manor Farm
Concat multiple C++ strings at once?
Yes, to avoid expensive memory waste use the stringstream
std::stringstream might be it, but I don't know how exactly it works.
this is how it works: include the sstream, create an object, append to it as much as you need using the stream operator << get the result as string calling the function str
example:
#include <sstream>
std::stringstream mySS;
mySS << "Hello" << " World!" << "end!!" << " Foo";
and when you are done
std::string stringResult = mySS.str();
How do I concatenate const/literal strings in C?
In C, "strings" are just plain char
arrays. Therefore, you can't directly concatenate them with other "strings".
You can use the strcat
function, which appends the string pointed to by src
to the end of the string pointed to by dest
:
char *strcat(char *dest, const char *src);
Here is an example from cplusplus.com:
char str[80];
strcpy(str, "these ");
strcat(str, "strings ");
strcat(str, "are ");
strcat(str, "concatenated.");
For the first parameter, you need to provide the destination buffer itself. The destination buffer must be a char array buffer. E.g.: char buffer[1024];
Make sure that the first parameter has enough space to store what you're trying to copy into it. If available to you, it is safer to use functions like: strcpy_s
and strcat_s
where you explicitly have to specify the size of the destination buffer.
Note: A string literal cannot be used as a buffer, since it is a constant. Thus, you always have to allocate a char array for the buffer.
The return value of strcat
can simply be ignored, it merely returns the same pointer as was passed in as the first argument. It is there for convenience, and allows you to chain the calls into one line of code:
strcat(strcat(str, foo), bar);
So your problem could be solved as follows:
char *foo = "foo";
char *bar = "bar";
char str[80];
strcpy(str, "TEXT ");
strcat(str, foo);
strcat(str, bar);
How to do string concatenation efficiently in C++?
std::string
has a c_str()
method for getting a const char*
pointer, eg:
std::string folderpath = "something";
folderpath += "/" + dbName;
mkdir(folderpath.c_str());
folderpath += "/" + dbName;
foo((folderpath + ".index").c_str());
bar((folderpath + ".db").c_str());
That being said, in C++17 and later you should use the functions and classes in the <filesystem>
library (in earlier versions, you can use boost::filesystem instead), eg:
#include <filesystem>
namespace fs = std::filesystem;
fs::path folderpath = "something";
folderpath /= dbName;
fs::create_directory(folderpath);
folderpath /= dbName;
folderpath += ".index";
foo(folderpath.string().c_str());
folderpath.replace_extension(".db");
bar(folderpath.string().c_str());
string concatenation in c++
You can use std::to_string()
to convert your integers:
bool Grid::is_available(int x, int y) const
{
if (x < 0 || x >= dim[1] || y < 0 || y >= dim[0])
throw std::invalid_argument(
"is_available(" + std::to_string(x) + ", "
+ std::to_string(y) + "): Invalid coordinate input.");
return occupancy[x][y] == AVAILABLE;
}
How do I concatenate two strings in C?
C does not have the support for strings that some other languages have. A string in C is just a pointer to an array of char
that is terminated by the first null character. There is no string concatenation operator in C.
Use strcat
to concatenate two strings. You could use the following function to do it:
#include <stdlib.h>
#include <string.h>
char* concat(const char *s1, const char *s2)
{
char *result = malloc(strlen(s1) + strlen(s2) + 1); // +1 for the null-terminator
// in real code you would check for errors in malloc here
strcpy(result, s1);
strcat(result, s2);
return result;
}
This is not the fastest way to do this, but you shouldn't be worrying about that now. Note that the function returns a block of heap allocated memory to the caller and passes on ownership of that memory. It is the responsibility of the caller to free
the memory when it is no longer needed.
Call the function like this:
char* s = concat("derp", "herp");
// do things with s
free(s); // deallocate the string
If you did happen to be bothered by performance then you would want to avoid repeatedly scanning the input buffers looking for the null-terminator.
char* concat(const char *s1, const char *s2)
{
const size_t len1 = strlen(s1);
const size_t len2 = strlen(s2);
char *result = malloc(len1 + len2 + 1); // +1 for the null-terminator
// in real code you would check for errors in malloc here
memcpy(result, s1, len1);
memcpy(result + len1, s2, len2 + 1); // +1 to copy the null-terminator
return result;
}
If you are planning to do a lot of work with strings then you may be better off using a different language that has first class support for strings.
Related Topics
How to Printf Uint64_T? Fails With: "Spurious Trailing '%' in Format"
Increasing Accuracy of Solution of Transcendental Equation
How to Remove Certain Characters from a String in C++
Demote Boost::Function to a Plain Function Pointer
How to Catch Segmentation Fault in Linux
How to Pass a Reference to a Two-Dimensional Array to a Function
Semantics of Flags on Basic_Ios
Explicit Specialization of Template Class Member Function
Assigning Parsers to Auto Variables
Copy Constructor For a Class With Unique_Ptr
Initialize a Const Array in a Class Initializer in C++
How to Find Memory Leak in a C++ Code/Project
How to Print an Unsigned Char as Hex in C++ Using Ostream