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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15319859/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 19:15:44  来源:igfitidea点击:

How to concatenate two strings in C++?

c++

提问by Slashr

I have a private class variable char name[10]to which I would like to add the .txtextension so that I can open the file present in the directory.

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

How do I go about this?

我该怎么做?

It would be preferable to create a new string variable that holds the concatenated string.

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

回答by Nawaz

First of all, don't use char*or char[N]. Use std::string, then everything else becomes so easy!

首先,不要使用char*or char[N]。使用std::string,然后其他一切都变得如此简单!

Examples,

例子,

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

Easy, isn't it?

很简单,不是吗?

Now if you need char const *for some reason, such as when you want to pass to some function, then you can do this:

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

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

assuming this function is declared as:

假设这个函数被声明为:

some_c_api(char const *input, size_t length);

Explore std::stringyourself starting from here:

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

Hope that helps.

希望有帮助。

回答by nogard

Since it's C++ why not to use std::stringinstead of char*? Concatenation will be trivial:

既然是 C++ 为什么不使用std::string而不是char*?连接将是微不足道的:

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

回答by TonyK

If you were programming in C, then assuming namereally is a fixed-length array like you say, you have to do something like the following:

如果您使用 C 进行编程,那么假设name确实是您所说的固定长度数组,您必须执行以下操作:

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

You see now why everybody recommends std::string?

你现在明白为什么每个人都推荐了std::string吗?

回答by dtech

There is a strcat()function from the ported C library that will do "C style string" concatenation for you.

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

BTW even though C++ has a bunch of functions to deal with C-style strings, it could be beneficial for you do try and come up with your own function that does that, something like:

顺便说一句,尽管 C++ 有一堆函数来处理 C 风格的字符串,但它可能对您尝试并提出自己的函数来执行此操作是有益的,例如:

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

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

    char *result = new char[l1 + l2];

    // 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] = '
char s1[] = "file_name";
char *c = con(s1, ".txt");
'; return result; }

...and then...

...进而...

    char greeting[6] = {'H', 'e', 'l', 'l', 'o', '
std::string great = "Hello"s + " World"; // concatenation easy!
'}; 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

... the result of which is file_name.txt.

...的结果是file_name.txt

You might also be tempted to write your own operator +however IIRC operator overloads with only pointers as arguments is not allowed.

您可能还想自己编写,operator +但是不允许仅使用指针作为参数的 IIRC 运算符重载。

Also, don't forget the result in this case is dynamically allocated, so you might want to call delete on it to avoid memory leaks, or you could modify the function to use stack allocated character array, provided of course it has sufficient length.

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

回答by Madhurya Gandi

strcat(destination,source) can be used to concatenate two strings in c++.

strcat(destination,source) 可用于在 C++ 中连接两个字符串。

To have a deep understanding you can lookup in the following link-

要深入了解,您可以在以下链接中查找-

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

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

回答by i.AsifNoor

It is better to use C++ string class instead of old style C string, life would be much easier.

最好使用 C++ 字符串类而不是旧式 C 字符串,生活会容易得多。

if you have existing old style string, you can covert to string class

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

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

回答by S.M.

C++14

C++14

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

void stringconcat(char *str1, char *str2){
    while (*str1 != '##代码##'){
        str1++;
    }

    while(*str2 != '##代码##'){
        *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;
}

Answer on the question:

回答问题:

##代码##

回答by Kartik

##代码##