yiiit1
yiiit1

Reputation: 103

What is the best way to put a char* in between another one multiple times in c++?

I have a char* that looks like:

opt = "abcdefghijklmnop";

Now I have another (const) char* that is like;

home = getenv("HOME");

What I want to do is changing the char* opt by putting the char* home in between, something like:

opt = "a" + home + "b" + home + "c" + home + ...;

What is the best way to do it?

Upvotes: 2

Views: 81

Answers (2)

NathanOliver
NathanOliver

Reputation: 180500

If we define "best" as how error prone it is and take into account ease of use then in my opinion the best way is not to use a char* and instead use a std::string instead. With a std::string you can do

std::string foo = "World";
std::string builder = "Hello " + foo + "!";

Result

Hello World!

std::string also has a constructor that takes a const char* or a char* so you can still use it with your functions that return those. There is also a c_str() member function what will return a const char* so you can still use it with functions that take either a const char* or a char*

Upvotes: 4

Ali Kazmi
Ali Kazmi

Reputation: 1458

you better to use std::string as said by @kerrek SB. if using char * is necessary, you can use strcpy function as described here

Upvotes: 3

Related Questions