在C++中连接字符数组

15

我有以下代码,想要得到一个字符串,比如:"你好,你怎么样?"(这只是我尝试实现的示例)

我应该如何将这2个字符数组连接起来,并在中间添加“,”和结尾处添加“you?”呢?

到目前为止,这个代码可以将这两个数组连接起来,但我不确定如何将额外的字符添加到我想要生成的最终字符变量中。

#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;
}

3
使用 std::string。它比你使用数组的尝试更容易(因为数组具有固定大小,所以根本无法工作)。 - ghostofstandardspast
1
无关的提示:您调用了 #include <string>,但未对 std::string 进行任何操作。如果您正在操作 C 风格的字符串,那么您可能至少应该包含 #include <cstring>。但更好的解决方案可能是将输入转换为 std::string 类型,如果某些函数需要 c 字符串,则在您的 std::string 上调用 .c_str 方法。 - DavidO
1
你使用字符数组来表示字符串,有什么原因吗? - Drew Dormann
顺便提一句 - 输出后最好加上 '\n' - 在某些系统中,如果没有发送最后的换行符,则程序退出后可能不会显示文本(例如某些UNIX / Linux shell - 假设每个程序都会在每行末尾添加一个换行符 - 清除回到行首然后打印提示)。 - Tony Delroy
@Matimont 抱歉晚了... 我会这样做:char* f; char* b; std::string c; c.reserve(strlen(f) + strlen(b) + 2); ((c += f) += ' ') += b;,即直接将 C 字符串分配给 std::string,而不是产生额外的副本(foos/tests!),并且预留足够的内存可以避免 std::string 中的重新分配。 - Aconcagua
显示剩余4条评论
7个回答

13
在C++中,使用std::stringoperator+,这些都是专门设计用来解决类似于这样的问题的。
#include <iostream>
#include <string>
using namespace std;

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

4
这种方法的问题在于它使用字符串,而我需要连接两个字符。 - Matimont
你总是可以从 C 风格的字符串构建一个 std::stringstd::string myString(foo); - quantdev
我在问题的编辑部分添加了我的发现,它可以工作,但这是最好的方法吗? - Matimont

8
最好的方法是在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);

3
为什么在C++代码中你使用了malloc?此外,你忘记为空字符留出空间。 - Ed Heal
@EdHeal:谢谢,我添加了空字符。我不得不问你回来,那么为什么malloc在C++编译器中可以工作呢? - Nayana Adassuriya
4
因为如此-最初的C++代码被转换成了C。但是对于新代码,您应该使用new。而且,如果您拥有C++的所有额外功能,为什么要编写C代码呢? - Ed Heal

2
如果您不想使用字符串,可以通过使用另一个数组并在循环中将两个数组存储在其中来简单地完成此操作。
#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;
}


1
如果你注重性能,我建议避免使用 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' 以避免读取无效的内存。 - user904963

1

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

char[] + char[] + char[]

将一个数组转换为 std::string,并且它将:
std::string(char[]) + char[] + char[]

E.g.:

#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
}

-1
cout<<x<<y<<z<<" ";
char arr[3] = {x , y ,z};
ans.push_back(arr);

如果你想要在向量数组中进行推入操作。


-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;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接