在 C++ 中你通常使用std::string
对于字符串。这样你就可以连接+
操作员。例如:
std::string s = s1 + s2 + s3;
where s1
, s2
and s3
你的三根弦是否固定在std::string
变量。
如果你有s1
, s2
and s3
as char*
or const char*
然后你写得有点不同。
std::string s = s1; // calls const char* constructor
s += s2; // calls operator+=() overload that accepts const char*
s += s3; // and again
如果您确实想使用以 null 结尾的 C 字符串和 C 字符串函数,那么您可以使用strcpy
复制并strcat
连接。
char[SOME_LARGE_ENOUGH_VALUE] str;
strcpy(str, s1);
strcat(str, s2);
strcat(str, s3);
where s1
, s2
and s3
你的三个字符串是char*
or const char*
.
当然,选择SOME_LARGE_ENOUGH_VALUE
是有趣的部分。如果这是一个学习练习,那么您可能想了解如何动态分配字符串。
char *str = new char[strlen(s1) + strlen(s2) + strlen(s3) + 1];
然后您可以使用strcpy
, strcat
上面随机播放。但现在您有责任销毁您分配的原始内存。因此,考虑如何以稳健的方式做到这一点,然后使用std::string
!
从注释来看,您似乎想要连接三个字符串,然后将结果字符串传递给接受 C 字符串的低级哈希函数。所以,我建议你做所有的工作std::string
。仅在最后一刻,当您调用哈希函数时,才使用c_str()
函数得到一个const char*
连接字符串的表示。