【问题标题】:How to concatenate two strings in C++?如何在 C++ 中连接两个字符串?
【发布时间】:2013-03-10 07:13:51
【问题描述】:

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

我该怎么做?

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

【问题讨论】:

    标签: c++


    【解决方案1】:

    首先,不要使用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自己:

    希望对您有所帮助。

    【讨论】:

    • 这个字符串连接的时间复杂度是多少?
    • @d34th4ck3r:它是线性的。
    【解决方案2】:

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

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

    【讨论】:

    • 值得注意的是,在运行时性能方面,微不足道的使用带来了不小的代价。最坏的情况是,operator+= 执行释放和分配。堆分配是我们通常做的最昂贵的操作之一。
    【解决方案3】:

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

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

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

    【讨论】:

    • 你不认为这个答案与这个问题无关吗?
    • 我确实认为这是相关的,因为“那个家伙”使用的是 char 而不是 std::string。此外,它显示了一种在投票最多的答案中未显示的明确连接方式。至少我从中学到了一些东西。
    • 这也显示了一种在没有动态内存分配的情况下进行字符串连接的方法。除非我错了,否则 std::string 运算符 += 需要可能的重新分配。
    【解决方案4】:

    移植的 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 回答的评论。
    • 还有strncat()函数通常是更好的选择
    • @nogard: strncat 在这里无关紧要,因为我们已经知道第二个参数".txt" 的长度。所以它只是strncat(name, ".txt", 4),这对我们没有任何好处。
    【解决方案5】:

    C++14

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

    回答问题:

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

    【讨论】:

    • 谢谢!我不知道末尾的 's' 用于将文字刺痛成对象类型的字符串。这很方便!也让我想起了 python。
    • 但前提是你声明using namespace std::string_literals;
    【解决方案6】:

    strcat(destination,source) 在c++中可以用来连接两个字符串。

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

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

    【讨论】:

      【解决方案7】:

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

      【讨论】:

        【解决方案8】:
        //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;
        }
        

        【讨论】:

          猜你喜欢
          • 2012-01-17
          • 2019-11-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-02-11
          • 2011-11-04
          相关资源
          最近更新 更多