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

一笑奈何 提交于 2019-12-12 04:48:53

问题


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);


来源:https://stackoverflow.com/questions/17110407/best-way-to-add-a-char-prefix-to-a-char-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!