gpt4 book ai didi

c++ - 将几个不同的字符连接成 1 个字符串

转载 作者:行者123 更新时间:2023-11-28 00:31:40 25 4
gpt4 key购买 nike

我有几个 char 变量,其中包含各种字符,这些字符由我创建的一些逻辑填充。基本上我正在寻找一种方法将这些添加到我已经创建的字符串中,但我不确定如何用一种简单的方法来做到这一点,而不是将所有字符单独附加到字符串中,这特别慢。

string test;
char test1, test2, test3, test4, test5;
...Some logic here to populate the chars

test += test1 + test2, etc

上面的方法不起作用,因为它按字面意思将值加在一起,就像在 char 的整数值中那样在最后创建一个数字。这是我目前(而且效率很低)的方法:

test += test1;
test += test2;
test += test3;
test += test4;
test += test5;

有没有一种方法可以更简单地将这些字符连接成 1 个字符串?

注意:值得一提的是,我知道这种方法就足够了,但我也希望在这里提高性能

最佳答案

使用resize在字符串中留出足够的空间并使用 operator[] 放置您的字符:

std::string result = "hello"
char c1 = '1', c2 = 'F', c3 = '%';

size_t len = result.size();
result.resize(len + 3);
result[len] = c1;
result[len+1] = c2;
result[len+2] = c3;

结果:hello1F%

如果您的字符在数组中,使用 insert 会更简单:

   std::string result = "hello";
char c[10]; // 10 characters
result.insert(result.end(), &c[0], 10); // add 10 characters to end of string

关于c++ - 将几个不同的字符连接成 1 个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22689698/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com