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

C++StringCopy

C++ Problem Overview


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(a,b);

but whenever I use

string a = "text";
string b = "image";
strcpy(a,b);

I get this error: >functions.cpp: no matching function for call to strcpy(std::string&, std::string&)

How to copy 2 strings of string data type in C++?

C++ Solutions


Solution 1 - C++

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;

Solution 2 - C++

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"

Solution 3 - C++

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 ;

Solution 4 - C++

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMuhammad Arslan JamshaidView Question on Stackoverflow
Solution 1 - C++CaesarView Answer on Stackoverflow
Solution 2 - C++bames53View Answer on Stackoverflow
Solution 3 - C++th3an0malyView Answer on Stackoverflow
Solution 4 - C++user2133061View Answer on Stackoverflow