如何在 C + + 中连接两个字符串?

我有一个私有类变量 char name[10],我想在其中添加 .txt扩展名,以便打开目录中的文件。

我该怎么做?

最好创建一个保存连接字符串的新字符串变量。

325222 次浏览

既然是 C + + ,为什么不用 std::string代替 char*呢? 连接将是微不足道的:

std::string str = "abc";
str += "another";

首先,不要使用 char*char[N]。使用 std::string,然后一切都变得如此容易!

例如:

std::string s = "Hello";
std::string greet = s + " World"; //concatenation easy!

很简单,不是吗?

现在,如果出于某种原因需要 char const *,比如想要传递给某个函数,那么可以这样做:

some_c_api(s.c_str(), s.size());

假设这个函数声明为:

some_c_api(char const *input, size_t length);

自己从这里开始探索 std::string:

希望能帮上忙。

从移植的 C 库中有一个 Strcat ()函数,它将为您执行“ C 样式字符串”连接。

顺便说一句,尽管 C + + 有很多函数可以处理 C 风格的字符串,但是如果你尝试自己创建一个函数来处理这些字符串,比如:

char * con(const char * first, const char * second) {
int l1 = 0, l2 = 0;
const char * f = first, * l = second;


// find lengths (you can also use strlen)
while (*f++) ++l1;
while (*l++) ++l2;


// allocate a buffer including terminating null char
char *result = new char[l1 + l2 + 1];


// then concatenate
for (int i = 0; i < l1; i++) result[i] = first[i];
for (int i = l1; i < l1 + l2; i++) result[i] = second[i - l1];


// finally, "cap" result with terminating null char
result[l1 + l2] = '\0';
return result;
}

然后..。

char s1[] = "file_name";
char *c = con(s1, ".txt");

结果是 file_name.txt

您可能也想编写自己的 operator +,但是 IIRC 操作符只使用指针重载,因为不允许使用参数。

另外,不要忘记这种情况下的结果是动态分配的,因此您可能需要对它调用 delete 以避免内存泄漏,或者您可以修改函数以使用堆栈分配的字符数组,当然前提是它有足够的长度。

如果你是用 C 语言编程,那么假设 name真的像你说的那样是一个固定长度的数组,你必须这样做:

char filename[sizeof(name) + 4];
strcpy (filename, name) ;
strcat (filename, ".txt") ;
FILE* fp = fopen (filename,...

现在你明白为什么大家都推荐 std::string了吧?

//String appending
#include <iostream>
using namespace std;


void stringconcat(char *str1, char *str2){
while (*str1 != '\0'){
str1++;
}


while(*str2 != '\0'){
*str1 = *str2;
str1++;
str2++;
}
}


int main() {
char str1[100];
cin.getline(str1, 100);
char str2[100];
cin.getline(str2, 100);


stringconcat(str1, str2);


cout<<str1;
getchar();
return 0;
}

Strcat (目标,源)可用于在 c + + 中连接两个字符串。

要深入了解,你可以在以下连结找到-

Http://www.cplusplus.com/reference/cstring/strcat/

最好用 C + + 字符串类代替旧式的 C 字符串,生活会容易得多。

如果您有现有的旧样式字符串,则可以转换为字符串类

    char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
cout<<greeting + "and there \n"; //will not compile because concat does \n not work on old C style string
string trueString = string (greeting);
cout << trueString + "and there \n"; // compiles fine
cout << trueString + 'c'; // this will be fine too. if one of the operand if C++ string, this will work too

C + + 14

std::string great = "Hello"s + " World"; // concatenation easy!

回答问题:

auto fname = ""s + name + ".txt";