在 C 中连接 char 数组

新手上路,请多包涵

我有以下代码,并希望得到一个字符,例如:“你好,你好吗?” (这只是我想要实现的一个例子)

如何连接 2 个字符数组并在中间添加“,”和“你”?在最后?

到目前为止,这连接了 2 个数组,但不确定如何将其他字符添加到我想要提出的最终 char 变量中。

 #include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    char foo[] = { "hello" };
    char test[] = { "how are" };
    strncat_s(foo, test, 12);
    cout << foo;
    return 0;
}

编辑:

这是我在您的所有回复后想出的。我想知道这是否是最好的方法?

 #include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    char foo[] = { "hola" };
    char test[] = { "test" };
    string foos, tests;
    foos = string(foo);
    tests = string(test);
    string concat = foos + "  " + tests;
    cout << concat;
    return 0;
}

原文由 Matimont 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 950
2 个回答

在 C++ 中,使用 std::stringoperator+ ,它是专门为解决此类问题而设计的。

 #include <iostream>
#include <string>
using namespace std;

int main()
{
    string foo( "hello" );
    string test( "how are" );
    cout << foo + " , " + test;
    return 0;
}

原文由 quantdev 发布,翻译遵循 CC BY-SA 3.0 许可协议

如果您关心性能,我建议避免 std::string 。相反,您可以使用字符数组。

 template <typename Result>
void concatenate(Result *res)
{
  return;
}

template <typename Result, typename T>
void concatenate(Result *res, T *str)
{
  strcat(res, str);
}

template <typename Result, typename First, typename ... T>
void concatenate(Result *res, First *f, T* ... next)
{
  strcat(res, f);
  concatenate(res, next...);
}

template <typename Result, typename First, typename ... T>
void concatStrings(Result *res, First *f, T* ... next)
{
  strcpy(res, f);
  concatenate(res, next...);
}

然后,您可以使用至少两个参数调用 concatStrings 函数,最多可以使用您需要的参数。

 /* You can remove constexpr as per your need. */
constexpr char hello[6] = "hello";
constexpr char sep[2] = ",";
constexpr char how[5] = " how";
constexpr char are[5] = " are";
constexpr char you[6] = " you?";

auto totalSize = strlen(hello) + strlen(sep) + strlen(how) + strlen(are) + strlen(you) + 5;

char statement[totalSize];
concatStrings(statement, hello, sep, how, are, you);
std::cout << statement << '\n';

原文由 Mrityunjay Tripathi 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题