gpt4 book ai didi

c++ - 如何连接字符?

转载 作者:行者123 更新时间:2023-11-30 04:45:43 24 4
gpt4 key购买 nike

我正在尝试连接字符串中的字符以检查它是否是一个单词。示例:

string s1 = "battle";
string s2 = "all";
string s3 = "lolo";
string s4 = "leaf";

string s5 = s1[0] + s2[0] + s3[0] + s4[0]

但 s5 是 unicode 的总和,而不是串联。我也尝试过使用 append 方法,例如

string s5 = "";
s5.append(s1[0]);

但这表示没有要调用的匹配函数。如果有任何帮助,我将不胜感激

最佳答案

这里有几种方法可以实现你想要的:

std::string s1 = "battle";
std::string s2 = "all";
std::string s3 = "lolo";
std::string s4 = "leaf";

{
// thanks to Mooing Duck for this one
std::string s5 = {s1[0], s2[0], s3[0], s4[0]/*, '\0'*/};
std::cout << s5 << "\n";
}
{
// thanks to Igor Tandetnik for this one
std::string s5 = std::string() + s1[0] + s2[0] + s3[0] + s4[0];
std::cout << s5 << "\n";
}
{
std::string s5;
for (const auto &str : { s1, s2, s3, s4 })
s5.push_back(str.at(0));
std::cout << s5 << "\n";

}
{
std::stringstream ss;
ss << s1[0] << s2[0] << s3[0] << s4[0];
std::string s5 = ss.str();
std::cout << s5 << "\n";
}
{
std::string s5 = std::string(1, s1[0]) + std::string(1, s2[0]) + std::string(1, s3[0]) + std::string(1, s4[0]);
std::cout << s5 << "\n";
}
{
std::string s5;
s5.resize(4);
s5[0] = s1[0];
s5[1] = s2[0];
s5[2] = s3[0];
s5[3] = s4[0];
std::cout << s5 << "\n";
}
{
std::string s5;
s5 += s1[0];
s5 += s2[0];
s5 += s3[0];
s5 += s4[0];
std::cout << s5 << "\n";
}

关于c++ - 如何连接字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57103474/

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