字符串连接C ++

时间:2011-09-06 22:49:53

标签: c++ concatenation

给定一个任意浮点数,比如-0.13,假设我们有一个算法,从左到右逐个计算这个数字的已知长度L的二进制字符串。

(我需要进行这个计算来计算粒子的Morton Key排序(给定的共同点),这反过来用于构建八叉树。我正在创建 每个x,y,z维度的二进制字符串

首先创建长度为L的字符数组,然后将此数组转换为字符串是否更好/更有效?即。

char ch[L];

for(i = 0; i < L; ++i)
{
    // calculation of ch[i]
}

//convert array into string

或者使用空字符串开始更好/更有效,然后将新计算的位连接到字符串中。即

string s = "";

for(i = 0; i < L; ++i)
{
    // calculation of ch[i]
    s = s + string(ch);
}

6 个答案:

答案 0 :(得分:5)

为什么不两者兼顾?

std::string myStr(L);

for(i = 0; i < L; ++i)
{
    // calculation of ch[i]
    myStr[i] = ch;
}

这会创建一个具有给定大小的std::string。然后你只需设置每个角色。如果您可以事先知道尺寸,那么可以正常工作。

或者,如果您想要一些安全的东西,即使您必须添加超过L个字符:

std::string myStr;
myStr.reserve(L);

for(i = 0; i < L; ++i)
{
    // calculation of ch[i]
    myStr.push_back(ch);
}

std::string::reserve预先分配存储空间,但如果需要,push_back会分配更多存储空间。如果您没有超过L个字符,那么您将只获得一个初始分配。

答案 1 :(得分:2)

使用后者,但在进入循环之前也请调用s.reserve(L)。这几乎与直接数组赋值一样有效,但仍然更容易理解。

编辑:其他答案建议使用push_back()。为他们投票。

  

补充工具栏:我不确定你在计算什么,但如果你只想生成数字的字符串表示,我建议你只需调用sprintf(),或将数字插入{std::stringstream。 1}}。

答案 2 :(得分:2)

我不确定我是否完全理解发生的转换,但我们有对象是有原因的。如果您首先使用std::string::reserve(),那么性能应该是微不足道的,并且显而易见的是。

string s;
s.reserve(L);
for(i = 0; i < L; ++i)
{
    // calculation of ch[i]
    string.push_back(ch);
}

如果绝对需要速度,您可以将字符串初始化为长度L,并绕过长度检查:

string s(L,'\0');
for(i = 0; i < L; ++i)
{
    // calculation of ch[i]
    string[i] = ch;
}

答案 3 :(得分:2)

你不能只使用预先分配长度的字符串吗?

string s(L, '\0');
for(i = 0; i < L; ++i)
{
    // calculation of ch[i]
}

答案 4 :(得分:2)

就个人而言,我可能已经过时了,但我使用

sprintf(char * str,const char * format,...);

从数字

创建字符串

sprintf(outString,“%f”,floatingPointNumber);

答案 5 :(得分:2)

如果您想要C ++方式,请使用ostringstream。这通常是更清晰的代码,更不容易出错,更容易阅读:

float f = ... // whatever you set it to
std::ostringstream s;
s << f;
std::string stringifiedfloat = s.str();
// now you have the float in a string.

或者,您可以使用C方式sprintf。这通常更容易出错,更难阅读,但性能更快:

float f = ... // whatever you set it to
char* buffer = new char[L];
sprintf(buffer, "%f", f);
// now you have the float in a string.

或者,你甚至可以使用boost lexical_cast。这比ostringstream具有更好的性能,并且比sprintf更好的可读性,但它让你依赖于boost:

float f = ... // whatever you set it to
std::string stringified = boost::lexical_cast<std::string>(f);
// now you have the float in a string.