How to copy a string of std::string type in C++?

前端 未结 4 1945
滥情空心
滥情空心 2020-12-24 12:25

I used the strcpy() function and it only works if I use C-string arrays like:

char a[6] = "text";
char b[6] = "image";
strcpy         


        
4条回答
  •  我在风中等你
    2020-12-24 13:07

    strcpy is only for C strings. For std::string you copy it like any C++ object.

    std::string a = "text";
    std::string b = a; // copy a into b
    

    If you want to concatenate strings you can use the + operator:

    std::string a = "text";
    std::string b = "image";
    a = a + b; // or a += b;
    

    You can even do many at once:

    std::string c = a + " " + b + "hello";
    

    Although "hello" + " world" doesn't work as you might expect. You need an explicit std::string to be in there: std::string("Hello") + "world"

提交回复
热议问题