我正在尝试将字符串中的字符连接起来,以检查它是否为单词。 示例:
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]);
但这表示没有匹配的函数要调用。 我将不胜感激
答案 0 :(得分:1)
有两种方法可以实现您想要的目标:
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";
}