Best way to add a char prefix to a char* in C++? [

2019-09-19 05:50发布

问题:

This question already has an answer here:

  • Prepending to a string 8 answers

I need to add a prefix ('X') to the char* (" is cool").

What is the BEST way to do this?

What is the easiest way?

char a = 'X';
char* b= " is cool";

I need:

char* c = "X is cool";

So far I tried strcpy-strcat, memcpy;

I'm aware this sounds as a stupid, unresearched question. What I was wondering is whether there is a way to add the char to the array without turning the char into a string.

回答1:

How about using C++ standard library instead of C library functions?

auto a = 'X';
auto b = std::string{" is cool"};
b = a+b;

or short:

auto a ='X';
auto b = a+std::string{" is cool"};

note that the explicit cast to string is mandatory.



回答2:

Maybe you can use a string instead of char* ?

std::string p = " is cool";
std::string x = 'X' + p;


回答3:

You're using C++, so for this purpose, don't use char* for strings, use std::string.

std::string str = std::string("X") + std::string(" is cool");
// Or:
std::string str = std::string("X") + " is cool";
// Or:
std::string str = 'X' + std::string(" is cool");
// Or:
std::string str = std::string{" is cool"};

That'll work like a charm, it expresses your intentions, it's readable and easy to type. (Subjective, yes, but whatever.)


In case you really need to use char* though, do note that char* b = " is cool"; is invalid because you're using a string literal. Consider using char b[] = " is cool";. That is an array of chars.

You would use strcat assuring that enough memory is allocated for the destination string.

char a[32] = "X"; // The size must change based on your needs.
                  // See, this is why people use std::string ;_;
char b[] = " is cool";

// This will concatenate b to a
strcat(a, b);

// a will now be "X is cool"

But seriously man, avoid the C-side of C++ and you will be happier and more productive [citation needed].



回答4:

Try,

char a[20] = "X";
char b[] = " is cool";
strcat(a,b);