【问题标题】:Concatenate char arrays in C++在 C++ 中连接 char 数组
【发布时间】:2014-08-06 22:46:08
【问题描述】:

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

如何连接 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;
}

【问题讨论】:

  • 使用std::string。它甚至比您尝试使用数组更容易(这根本不起作用,因为数组具有固定大小)。
  • 不相关:您正在调用 #include &lt;string&gt;,但对 std::string(s) 没有执行任何操作。如果您正在操作 C 风格的字符串,您可能至少应该包括 #include &lt;cstring&gt;。更好的解决方案可能是将输入转换为 std::string 类型,如果某些函数需要 c-string,请在 std::string 上调用 .c_str 方法。
  • 为什么你的 stringx 周围有大括号
  • 您使用char 的数组来表示您的字符串有什么原因吗?
  • 顺便说一句 - 在输出后输出 '\n' 是个好主意 - 在某些系统上,除非发送最后的换行符,否则在程序退出后文本可能不可见(例如,某些 UNIX/Linux shells - 假设每个程序都会用换行符结束每一行 - 清除回行首然后打印提示符)。

标签: c++ arrays char concatenation


【解决方案1】:

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

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

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

【讨论】:

  • 这种方法的问题是使用字符串,我需要连接 2 个字符
  • 您始终可以从 C 风格的字符串构建 std::stringstd::string myString(foo);
  • 我在问题的编辑部分添加了我的发现,它有效,但它是最好的方法吗? ——
【解决方案2】:

最好的办法是在 C++ 中使用 std::string 作为其他答案。如果您真的需要使用 char 尝试这种方式。没有测试。

const char* foo = "hello";
const char* test= "how are";

char* full_text;
full_text= malloc(strlen(foo)+strlen(test)+1); 
strcpy(full_text, foo ); 
strcat(full_text, test);

【讨论】:

  • 为什么在 C++ 代码中使用malloc?你也忘了为空字符留出空间
  • @EdHeal:谢谢,我添加了空字符。我必须回问你,为什么malloc 在 C++ 编译器中工作?
  • 因为它确实如此 - 最初 C++ 代码已转换为 C。但对于新代码,您应该使用 new。还有,当你拥有 C++ 的所有额外能力时,为什么还要编写 C 代码
【解决方案3】:

是的,在 C++ 中使用+ 运算符进行字符串连接。 但这不起作用:

char[] + char[] + char[]

将一个数组转换为 std::string ,它将:

std::string(char[]) + char[] + char[]

例如:

#include <iostream>

int main()
{
    const char a[] = "how ";
    const char b[] = "are ";
    const char c[] = "you ";

    std::cout << std::string( a + b + c ) << "\n"; // Error
    std::cout << std::string(a) + b + c  << "\n"; // Fine
}

【讨论】:

    【解决方案4】:

    如果您不想使用字符串,您可以简单地通过获取另一个数组并使用循环将两个数组存储在其中来完成

    #include<iostream>
    #include<stdlib.h>
    #include<cstdio>
    using namespace std;
    int main(){
        char fname[30],lname[30],full_name[60];
        int i,j;
        i=0;j=0; // i is index of fname and j is index for lname
        cout<<"Enter your first name: ";
        gets(fname);
        cout<<"Enter your last name: ";
        gets(lname);
        for (i;fname[i]!='\0';i++){
            full_name[i] = fname[i];
        }
        cout<<"i ="<<i;
        full_name[i]=' ';
        i = i + 1;
        for (i,j;lname[j]!='\0';i++,j++){
            full_name[i] = lname[j];
        }
        cout<<"Your full name is: "<<full_name<<endl;
        system("pause");
        return 0;
    }
    
    【解决方案5】:
    cout<<x<<y<<z<<" ";
    char arr[3] = {x , y ,z};
    ans.push_back(arr);
    

    如果你想推入向量数组。

    【讨论】:

      【解决方案6】:

      如果您担心性能问题,我建议您避免使用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';
      

      【讨论】:

      • std::string 几乎适用于任何情况。通常只有在与其他使用数组的代码交互时才需要使用数组。事实上,std::string 在很多常见场景下都更快。例如,对于std::string,查找其大小为 O(1),对于 C 样式字符串,查找其大小为 O(n)。此外,由于std::string 知道正在使用的内存,算法可以用一条指令检查多个字节,而 C 风格的字符串必须首先检查一个字节不是 ''\0' 以避免读取无效内存。
      【解决方案7】:

      2 个字符数组

        char foo[] = { "hello " };
        char test[] = { "how are" };
        char concat[50];
        char x='X'; //Any Temporary Variable
        int i;
        for(i=0; x!='\0'; i++){ //x is not NULL
          x = foo[i];
          concat[i] = x;
        }
        x = 'D';
        i--;
        for (int k = 0; x!='\0'; i++){
          x = test[k];
          concat[i] = x;
          k++;
        }
        cout<<"Concat Array is: "<<concat;
      

      【讨论】:

        猜你喜欢
        • 2011-01-14
        • 1970-01-01
        • 1970-01-01
        • 2017-09-13
        • 2012-05-18
        • 1970-01-01
        • 2013-02-26
        • 1970-01-01
        相关资源
        最近更新 更多