0

我需要为 char* 添加一个前缀('X')(“很酷”)。

做这个的最好方式是什么?

最简单的方法是什么?

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

我需要:

char* c = "X is cool";

到目前为止,我尝试了 strcpy-strcat、memcpy;

我知道这听起来是一个愚蠢的、未经研究的问题。我想知道是否有一种方法可以将 char 添加到数组而不将 char 转换为字符串。

4

4 回答 4

6

使用 C++ 标准库而不是 C 库函数怎么样?

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

或简称:

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

请注意,强制转换为字符串。

于 2013-06-14T14:12:39.540 回答
2

也许您可以使用字符串而不是 char* ?

std::string p = " is cool";
std::string x = 'X' + p;
于 2013-06-14T14:10:50.230 回答
1

您正在使用 C++,因此为此目的,不要char*用于字符串,请使用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"};

这就像一个魅力,它表达了你的意图,它可读且易于输入。(主观的,是的,但无论如何。)


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].

于 2013-06-14T14:13:25.180 回答
0

尝试,

char a[20] = "X";
char b[] = " is cool";
strcat(a,b);
于 2013-06-14T14:10:07.627 回答