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


100

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

我该怎么办?

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

Answers:


160

首先,请勿使用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从这里开始探索自己:

希望能有所帮助。


3
此字符串串联的时间复杂度是多少?
d34th4ck3r

@ d34th4ck3r:它是线性的。
纳瓦兹

30

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

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

1
值得注意的是,对于运行时性能而言,微不足道的使用附带了不小的代价。最坏的情况是,它同时operator+=执行解除分配和分配。堆分配是我们通常最昂贵的操作之一。
IInspectable

15

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

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

您现在知道为什么每个人都推荐std::string吗?


1
您看不到那个人用C ++而不是C问了一个问题吗?
IcyFlame

21
您看不到我说“如果您正在编程...”吗?
TonyK

您认为这个答案与这个问题无关吗?
IcyFlame

9
我确实认为这很重要,因为“那个家伙”使用的是char而不是std :: string。此外,它还显示了一种明确的级联方式,这在投票最多的答案中并未体现出来。至少我从中学到了一些东西。
gvegayon

1
这也显示了一种无需动态内存分配即可进行字符串连接的方法。除非我错了,否则std :: string运算符+ =需要重新分配。
阿什莉·邓肯

7

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

顺便说一句,即使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] = '\0';
    return result;
}

...然后...

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

...的结果是file_name.txt

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

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


请参阅我对IcyFlame答案的评论。
TonyK

3
还有strncat()功能通常是更好的选择
nogard

@nogard:strncat在这里无关紧要,因为我们已经知道第二个参数的长度".txt"。这样就不会strncat(name, ".txt", 4)带来任何好处。
TonyK


0

最好使用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

0

C ++ 14

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

回答以下问题:

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

-2
//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;
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.