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

前端 未结 4 1933
滥情空心
滥情空心 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:05

    Caesar's solution is the best in my opinion, but if you still insist to use the strcpy function, then after you have your strings ready:

    string a = "text";
    string b = "image";
    

    You can try either:

    strcpy(a.data(), b.data());
    

    or

    strcpy(a.c_str(), b.c_str());
    

    Just call either the data() or c_str() member functions of the std::string class, to get the char* pointer of the string object.

    The strcpy() function doesn't have overload to accept two std::string objects as parameters. It has only one overload to accept two char* pointers as parameters.

    Both data and c_str return what does strcpy() want exactly.

    0 讨论(0)
  • 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"

    0 讨论(0)
  • 2020-12-24 13:11

    You shouldn't use strcpy() to copy a std::string, only use it for C-Style strings.

    If you want to copy a to b then just use the = operator.

    string a = "text";
    string b = "image";
    b = a;
    
    0 讨论(0)
  • 2020-12-24 13:26

    strcpy example:

    #include <stdio.h>
    #include <string.h>
    
    int main ()
    {
      char str1[]="Sample string" ;
      char str2[40] ;
      strcpy (str2,str1) ;
      printf ("str1: %s\n",str1) ;
      return 0 ;
    }
    

    Output: str1: Sample string

    Your case:

    A simple = operator should do the job.

    string str1="Sample string" ;
    string str2 = str1 ;
    
    0 讨论(0)
提交回复
热议问题